0

I'm learning to get used to the pointers in C and I have a question about them that I coudln't understand. Anyways, why this code gives segmentation fault?

void print_arr(const char *p_array[]){
      int index;
      for(index = 0; p_array[index] != 0; index++)
              printf("%s\n", *p_array[index]);
}

while the one without a '*' in printf work perfectly

    void print_arr(const char *p_array[]){
          int index;
          for(index = 0; p_array[index] != 0; index++)
                  printf("%s\n", p_array[index]);
    }

The whole code is taken from here
Click Here. Thanks!

2
Contributors
2
Replies
3
Views
4 Years
Discussion Span
Last Post by Kert
1

p_array is a pointer. When you use the subscript operator, that pointer is dereferenced. In other words p_array[index] is functionally identical to *(p_array + index). Now, when you dereference p_array, the result is also a pointer, specifically a pointer to char. So this line is correct because the %s specifier of printf() expects a pointer to char:

printf("%s\n", p_array[index]);

If you further dereference the pointer, you get a char value (not a pointer). The reason you're getting an access violation is because printf() treats that value as an address, because you told it using the %s specifier that you were providing a valid address in the form of a pointer. In other words, you lied to printf(). ;)

1

Thanks! But is it possible to access the p_array with pointer as well instead of using int index? I have tried to do it but without success. Here is an example what I thought...

main(){
  float fa[ARSZ], *fp1, *fp2;

  fp1 = fp2 = fa; /* address of first element */
  while(fp2 != &fa[ARSZ]){
          printf("Difference: %ld\n", (long)(fp2-fp1));
          fp2++;
  }
  exit(EXIT_SUCCESS);
}

E: found it

void print_arr(const char **p_array){
      while(*p_array)
              printf("%s\n", *p_array++);
}

Edited by Kert

Votes + Comments
Kudos for the finding your own answer
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.