Abdessalem Boukil
Abdessalem Boukil

Reputation: 65

C Printing same array produces different results using two methods

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 ?

Upvotes: 2

Views: 124

Answers (1)

CIsForCookies
CIsForCookies

Reputation: 12817

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]

Upvotes: 4

Related Questions