For loop stops for no reason

扶醉桌前 提交于 2020-01-06 19:57:29

问题


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;
}

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

and pattern repeats this all the way up to

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

then crashes. Any ideas?


回答1:


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)++



来源:https://stackoverflow.com/questions/35269845/for-loop-stops-for-no-reason

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!