Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers and Arrays in C, Need for more Understanding

Tags:

arrays

c

pointers

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
like image 850
Madona wambua Avatar asked Jul 04 '15 18:07

Madona wambua


2 Answers

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";
like image 131
haccks Avatar answered Oct 10 '22 14:10

haccks


In C, a[b], b[a], *(a+b) are equivalent and there's no difference between these 3. So you only have 2 cases:

char *name = "Madonah"; /* case 1 */

and

char name3 [7] = "Madonah"; /* case 2 */

The former is a pointer which points to a string literal. The latter is an array of 7 characters.

which one is preferred depends on your usage of name3.

If you don't intend to modify then the string then you can use (1) and I would also make it const char* to make it clear and ensure the string literal is not modified accidentally. Modifying string literal is undefined behaviour in C

If you do need to modify it then (2) should be used as it's an array of characters that you can modify. One thing to note is that in case (2), you have explicitly specified the size of the array as 7. That means the character array name3 doesn't have a null terminator (\0) at the end. So it can't be used as a string. I would rather not specify the size of the array and let the compiler calculate it:

char name3 [] = "Madonah"; /* case 2 */
/* an array of 8 characters */
like image 11
P.P Avatar answered Oct 10 '22 14:10

P.P