Question

I am writing code to read a PPM file into a struct pixel_type array containing 3 unsigned chars r,g, and b. The code that causes problems looks like this:

struct pixel_type pArray[width][height], *pPtr[width][height];
pPtr[width][height] = &pArray[width][height];

for(h = 0; h < height; h++)
{
    for(w = 0; w < width; w++)
    {
        fscanf(in, "%c%c%c", pPtr[w][h]->r, pPtr[w][h]->g, pPtr[w][h]->b);
    }
}

When compiling, I get this message for all 3 "%c"s:

warning:

format â%câ expects argument of type âchar *â, but argument (3,4, or 5) has type âintâ [-Wformat]

What would be the best way to read the pixel values into the struct pixel_type array?

struct pixel_type
{
    unsigned char r;
    unsigned char g;
    unsigned char b;
};
Was it helpful?

Solution

You only need one temporary pointer, not a whole array of them.

struct pixel_type {
    unsigned char r;
    unsigned char g;
    unsigned char b;
    };

main()
{   
    struct pixel_type pArray[10][10], *pPtr;
    int height = 10, width = 10, h, w;
    char buf[32];

    /* testing */

    strcpy(buf, "abc");

    for(h = 0; h < height; h++) {
        for (w = 0; w < width; w++) {
            pPtr = &pArray[width][height];
            /* testing */
            sscanf(buf, "%c%c%c", &pPtr->r, &pPtr->g, &pPtr->b);
            /* fscanf(in, "%c%c%c", &pPtr->r, &pPtr->g, &pPtr->b); */
        }
    }
}

OTHER TIPS

Changing your 2D array of pointers pPtr[width][height] to a pointer pPtr will solve your problem.

You don't need to declare a pointer to the array *pPtr[width][height], since pArray[width][height] is already an array and this:

pArray[0][0];

is equivalent to this:

*pArray;

In the same way that this:

&pArray[0][0];

Is equivalent to this:

pArray;

So you just need to point the address of where your data is (inside of the structure), after the pointer or the array had already been deferenced.

struct pixel_type pArray[width][height];

for(h = 0; h < height; h++)
{
    for(w = 0; w < width; w++)
    {
        fscanf(in, "%c%c%c", &(pArray[w][h].r), &(pArray[w][h].g), &(pArray[w][h].b));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top