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!

Recommended Answers

All 2 Replies

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

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++);
}
commented: Kudos for the finding your own answer +11
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.