Assigning strings to pointer in C Language
c, pointers, string
Solution
`char *c; c="name";`
If you observe here, you are not assigning string "name" to variable c but, you are assigning the base address of memory where `name` is stored into variable `c`.
The string `name` is stored in the string table created by the compiler, all the strings of this form are stored in string table, this string table is a const type, meaning you cannot write again to this location. e.g you can try these two lines `char *p = "Hello" ; strcpy(p,"Hi");`. While compilation you will get error at second line.
`int *c; c = 10;`
In the above code you are creating an integer pointer and assigning 10 to it, the compiler here understands that you are assigning 10 as an address. One more thing you need to understand is all the pointer variables store unsigned interger constants only. So even if it is `char *c` or `int *c` in both of these cases the variable c stores an unsigned integer only.
Problem
I am a new learner of C language, my question is about pointers. As far I 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. If there is something I am missing about pointers plz explain.