Home > Software engineering >  Arrays and pointers in C, two questions
Arrays and pointers in C, two questions

Time:05-28

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?

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?

CodePudding user response:

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.

  • Related