Syombua Muthoka Syombua Muthoka - 18 days ago 5
C Question

Pointers and Arrays in C, Need for more Understanding

I was doing some pointers and arrays practice in C and I noticed all my four methods returned the same answer.My question is are there disadvantages of using any one of my below methods? I am stunned at how all these four give me the same output. I just noticed you can use a pointer as if it was an array and you can also use an array as if it was a pointer?

char *name = "Madonah";
int i= 0;
for (i=0;i<7; i++){
printf("%c", *(name+i));
}

char name1 [7] = "Madonah";
printf("\n");
int j= 0;
for (j=0;j<7; j++){
printf("%c", name1[j]);
}

char *name2 = "Madonah";
printf("\n");
int k= 0;
for (k=0;k<7; k++){
printf("%c", name2[k]);
}

char name3 [7] = "Madonah";
printf("\n");
int m= 0;
for (m=0;m<7; m++){
printf("%c", *(name+m));
}


Results:

Madonah
Madonah
Madonah
Madonah

Answer

It is true that pointers and arrays are equivalent in some context, "equivalent" means neither that they are identical nor even interchangeable. Arrays are not pointers.
It is pointer arithmetic and array indexing that are equivalent, pointers and arrays are different.

which one is preferable and the advantages/Disadvantages?

It depends how you want to use them. If you do not wanna modify string then you can use

char *name = "Madonah";  

It is basically equivalent to

char const *name = "Madonah";  

*(name + i) and name[i] both are same. I prefer name[i] over *(name + i) as it is neat and used most frequently by C and C++ programmers.

If you like to modify the string then you can go with

char name1[] = "Madonah";