pointers - In C, why can't an integer value be assigned to an int* the same way a string value can be assigned to a char*? -


i've been looking through site haven't found answer 1 yet.

it easiest (for me @ least) explain question example.

i don't understand why valid:

#include <stdio.h>  int main(int argc, char* argv[]) {   char *mystr = "hello"; } 

but produces compiler warning ("initialization makes pointer integer without cast"):

#include <stdio.h>  int main(int argc, char* argv[]) {   int *myint = 5; } 

my understanding of first program creates variable called mystr of type pointer-to-char, value of address of first char ('h') of string literal "hello". in other words initialization not pointer, define object ("hello" in case) pointer points to.

why, then, int *myint = 5; seemingly not achieve analogous this, i.e. create variable called myint of type pointer-to-int, value of address of value '5'? why doesn't initialization both give me pointer , define object pointer points to?

in fact, can using compound literal, feature added language 1999 iso c standard.

a string literal of type char[n], n length of string plus 1. array expression, it's implicitly converted, in not contexts, pointer array's first element. this:

char *mystr = "hello"; 

assigns pointer mystr address of initial element of array contents "hello" (followed terminating '\0' null character). incidentally, it's safer write:

const char *mystr = "hello"; 

there no such implicit conversions integers -- can this:

int *ptr = &(int){42}; 

(int){42} compound literal, creates anonymous int object initialized 42; & takes address of object.

but careful: array created string literal has static storage duration, object created compound literal can have either static or automatic storage duration, depending on appears. means if value of ptr returned function, object value 42 cease exist while pointer still points it.

as for:

int *myint = 5; 

that attempts assign value 5 object of type int*. (strictly speaking it's initialization rather assignment, effect same). since there's no implicit conversion int int* (other special case of 0 being treated null pointer constant), invalid.


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -