why in the below code int *p = 22 will give compile time error and ptr will print the value successfully .
int main()
{
/*taking a character pointer and assigning a string to it*/
char *ptr = "Stackoverflow" ; //correct
/*taking a int pointer and assigning a string to it*/
int *p = 22 ; //incorrect
printf("%s",ptr); // correct and print
printf("%d",p); //incorrect and give compile time error.
return 0;
}
This line assigns the memory address to be 22. This is incorrect. While this line will compile with only a warning, it will crash your program at runtime when you try to access memory address 22 later in the code.
This will give you the result you're looking for:
Also
%s
takes a pointer to char, where it is a null terminated string, while%d
takes anint
, not anint*
.If you have a character array as for example
then the array designator used in expressions it is converted to pointer to its first element. So you may write
The pointer
ptr
now points to the first character of the arrays
.String literals in C are also represented like character arrays and stored in memory like character arrays with the static storage duration.
So for example the string literal
"Stackoverflow"
has the typechar[14]
(including the terminating zero).So then you write
then this statement in fact the same if there would be
As for this statement
then the integer literal is not converted to a pointer to itself. It represents literally the number 22 and nothing more.
So the compiler issues a message because if you want that the pointer indeed contained the integer value 22 then you have to use a casting.
The expression
always yields
true
.While this expression
is not necessary yields
true
because depending on compiler options the compiler can place coincidental string literals in different memory areas. And in this expression it is the pointers to the first characters of the string literals that are compared.Take into account that if you are going to output an integer object pointed to by a pointer you need to use dereferencing. So in any case instead of
you should write
Or if you want to output the value stored in a pointer you have to use another format specifier
Because the string is actually an array of char's and when assigning an array to a variable, the arrays will behave as a pointer to the first element of the array. This can be confusing. More on this here:
when does a array act as a pointer in c?
The integer on the other hand is just an integer, not an array of integers.