Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Arrays and pointers in C, two questions

This program works in C:

#include <stdio.h>


int main(void) {
    char a[10] = "Hello";
    char *b = a;
    
    printf("%s",b);
}

There are two things I would expect to be different. One is that we in the second line in the main write: "char *b = &a", then the program is like this:

#include <stdio.h>


int main(void) {
    char a[10] = "Hello";
    char *b = &a;
    
    printf("%s",b);
}

But this does not work. Why is that? Isn’t this the correct way to initialize a pointer with an adress?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The second problem I have is in the last line we should have: printf("%s",*b) so the program is like this:

#include <stdio.h>


int main(void) {
    char a[10] = "Hello";
    char *b = a;
    
    printf("%s",*b);
}

But this gives a segmentation fault. Why does this not work? Aren’t we supposed to write "*" in front of a pointer to get its value?

>Solution :

There is a special rule in C. When you write

char *b = a;

you get the same effect as if you had written

char *b = &a[0];

That is, you automatically get a pointer to the array’s first element. This happens any time you try to take the "value" of an array.

Aren’t we supposed to write "*" in front of a pointer to get its value?

Yes, and if you wanted to get the single character pointed to by b, you would therefore need the *. This code

printf("first char: %c\n", *b);

would print the first character of the string. But when you write

printf("whole string: %s\n", b);

you get the whole string. %s prints multiple characters, and it expects a pointer. Down inside printf, when you use %s, it loops over and prints all the characters in the string.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading