本文介绍了For循环无故停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图编写一个程序来读取ppm文件并将其存储在内存中,我已经将所有工作都按颜色进行了,此功能给我带来了问题:

So I'm trying to make a program to read a ppm file and store it in memory, I've got everything working up to the colors, this function is giving me problems:

typedef struct{
    int red, green, blue;
} COLOR;

COLOR * getNextColor(FILE *fd);

COLOR **getColors(FILE *fd, int width, int height){
    printf("\nentered get colors");
    COLOR **colors = malloc(sizeof(COLOR*)*height);
    printf("\nallocated %d space height",height);

    int i,j;
    for(i = 0; i < height; i++, colors++){
        *colors = malloc(sizeof(COLOR)*width);
        printf("\nallocated %d space width",width);
        for(j = 0; j < width; j++, *colors++){
            printf("\nlooping through to get the colors for point (%d,%d)", j,i); 
            //*colors = getNextColor(fd);
        }
        *colors -= width;
        printf("\nmoved the pointer for *colors back %d spaces",width);
    }

    colors -= height;
    printf("\nmoved the pointer for colors back %d spaces",height);

    return colors;
}

我传入的文件指针当前指向第一种颜色的第一位,宽度= 400,高度为530.输出如下所示:

I'm passing in a file pointer that is currently pointing at the first digit of the first color, the width = 400 and height is 530. The output looks like this:

allocated 530 space height
allocated 400 space width
looping through to get the colors for point (0,0)
looping through to get the colors for point (1,0)
looping through to get the colors for point (2,0)
...
looping through to get the colors for point (398,0)
looping through to get the colors for point (399,0)
moved the pointer for *colors back 400 spaces
allocated 400 space width
looping through to get the colors for point (0,1)
looping through to get the colors for point (1,1)
...
looping through to get the colors for point (398,1)
looping through to get the colors for point (399,1)
moved the pointer for *colors back 400 spaces
allocated 400 space width

并且图案一直重复直到

looping through to get the colors for point (399,36)

然后崩溃.有什么想法吗?

then crashes. Any ideas?

推荐答案

*colors++出现问题,这可能并不意味着您认为它做了什么.这是由于运算符优先级引起的,最高优先级具有后缀递增/递减运算符,而较低优先级具有间接性.所以*colors++实际上是*(colors)++的意思,没有多大意义.您可能是说(*colors)++

There is a problem with *colors++ that does not probably mean what you think it does. This is due to operator precedence, highest precedence has postfix increment/decrement operators and lower precedence has indirection. So *colors++ actually meanst *(colors)++ which doesn't make much sense. You probably meant (*colors)++

这篇关于For循环无故停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 03:25