2

I'm experimenting with C void functions and strings. I've tried this program:

#include <stdio.h>
#include <string.h>

void print(char** test);
int main(){
    char* test = "abcdef";
    print(&test);
    return 0;
}
void print(char** test){
    for(int i=0;i<strlen(*test);i++)
        printf("%c\n",*test[i]);
}

It prints for me the first a A � then segmentation fault. But after changing *test[i] to *(*test+i) which is pretty much the same thing it works for me as expected.

Is there any subtle difference *test[i] and *(*test+i) if not, why my code works in second examples meanwhile it doesn't in the first ?

1 Answers1

4

test is a char**. As Some programmer dude commented, the [] takes precedence over the * so your for loop is executed like this:

  1. *test[0] == *(test[0]) == 'a'
  2. *test[1] == *(test[1]) == *(some other address that is saved in memory after &test) => UB

Either use one indirection in the whole program (i.e. *, not ** and &test), or use (*test)[i]

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124