1

I am trying to create a pointer to an array of structs and pass it to a function where I will change values of the struct.

Could someone please explain me why my code seems to not correctly allocate the memory for the array as execution of the compiled version fails for 27pixels if I store both integer variables in the struct whereas it works for 27pixels if I only store one integer variable?

    typedef struct Pixel
    {
        int label;
        int area;
    }Pixelmap;

    int change_pixel(Pixelmap* pixelmap)
    {
         for (x = 0; x < dimx*dimy*dimz; x++)
        {
            pixelmap[x].label = x; /* or malloc and strcpy */
            pixelmap[x].area = 1;
            printf("%i\n",pixelmap[x].label);
        }
        return 1;
    }

    int main()
    {
        Pixelmap *pm;
        pm = malloc(dimx*dimy*dimz * sizeof (struct Pixel));
        change_pixel(&pm);
        printf("End!\n");
        free(pm);
        return 0;
    }
2
  • 2
    change_pixel(&pm); ====> change_pixel(pm); and turn up your compiler warnings as high as they can go. you should have been notified of an incompatible type. Commented May 7, 2015 at 17:30
  • Perhaps change_pixel should be renamed set_pixel since the memory allocated by malloc is uninitialised. Commented May 7, 2015 at 17:37

2 Answers 2

3

You passed a the address of the pointer to change_pixel, but it's expecting the pointer itself. It should be:

change_pixel(pm);

I'm surprised you didn't get a warning from the compiler about the incorrect type of argument. The argument is declared Pixelmap*, but you passed Pixelmap**.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot. i will pay more attention to warnings next time!
0

Not sure if it is a typo but you allocate

sizeof(struct Pixel)

it should be

sizeof(struct Pixelmap)

as in

pm = malloc(dimx*dimy*dimz * sizeof (struct Pixelmap));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.