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!

Recommended Answers

All 4 Replies

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

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. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.