C Programming – Assigning Strings to Pointers

cpointersstrings

My question is about pointers in C. As far as I've learned and searched, pointers can only store addresses of other variables, but cannot store the actual values (like integers or characters). But in the code below the char pointer c actually storing a string. It executes without errors and give the output as 'name'.

#include <stdio.h>
main()
{
  char *c;
  c="name";
  puts(c);
}

Can anyone explain how a pointer is storing a string without any memory or if memory is created where it is created and how much size it can be created?

I tried using it with the integer type pointer

#include <stdio.h>
main()
{
  int *c;
  c=10;
  printf("%d",c);
}

but it gave an error

cc     test.c   -o test
test.c: In function ‘main’:
test.c:5:3: warning: assignment makes pointer from integer without a cast   [enabled by default]
c=10;
^
test.c:6:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%d",c);
^

Pointers stores the address of variable then why is integer pointer different from character pointer?

Is there something I am missing?

Best Answer

This is just the way string literals work in C. String literals like "name" are arrays of characters, it is equivalent to the five element array {'n', 'a', 'm', 'e', '\0'}. For the code

char *c;
c="name";

the environment reserves memory for the above array already at initialization time, when the program is loaded from disk into memory. At run time, the adress of the beginning of that array is assigned to c.

Note the first piece of code of yours is not equivalent to the second, because in the first piece you assign a string literal (and not a character like 'n') to a char* variable. In the second, you try to assign an int (and not an int array) to an int*.

Here is a tutorial on strings and pointers in C with a more detailed explanation.