Hello,

I've an external/global array that is used every where in my code.

// global.h file
short is_valid[10];

I initialize my array somewhere in the code and I want to check if everything works. When I try to print the values of the array, I get segmentation fault.

// .c file
short *pValid = is_valid; 
memset(&pValid, 1, 10 * sizeof (short));
for (i = 0; i < 10; i++)
  printf("%d ", *(&pValid[i])); // the seg fault is here
printf("\n");

What do you recommend?
Thank you!

Hello,

I've an external/global array that is used every where in my code.

// global.h file
short is_valid[10];

I initialize my array somewhere in the code and I want to check if everything works. When I try to print the values of the array, I get segmentation fault.

// .c file
short *pValid = is_valid; 
memset(&pValid, 1, 10 * sizeof (short));
for (i = 0; i < 10; i++)
  printf("%d ", *(&pValid[i])); // the seg fault is here
printf("\n");

What do you recommend?
Thank you!

Why are passing the address of the pointer?

memset(&pValid, 1, 10 * sizeof (short));

shouldn't you be passing the pointer value..

memset(pValid, 1, 10 * sizeof (short));

Thank you guys.

Why are passing the address of the pointer?
memset(&pValid, 1, 10 * sizeof (short));
shouldn't you be passing the pointer value..
memset(pValid, 1, 10 * sizeof (short));

I don't know why I'm passing &pValid instead of pValid, but with pValid it doesn't work.
Actually, in the .h file I've this:

// global.h file
struct myStructure {
short is_valid[10];
};

so short is_valid[10] is included in a structure. In the .c file, short *pValid = is_valid; is not exactly what I mentioned, but short *pValid = myStructure->is_valid;

I think I'm not gonna use a pointer. It's easy to use the array directly.

Actually, in the .h file I've this:

so short is_valid[10] is included in a structure. In the .c file, short *pValid = is_valid; is not exactly what I mentioned, but short *pValid = myStructure->is_valid;

In the future, try to avoid "paraphrasing" code -- it tends to have more than a 50% chance of introducing other problems. ;)

This article has been dead for over six months. Start a new discussion instead.