c - Why can't we assign int* x=12 or int* x= "12" when we can assign char* x= "hello"? -


what correct way use int* x? mention related link if possible unable find one.

a string literal creates array object. object has static storage duration (meaning exists entire execution of program), , initialized characters in string literal.

the value of string literal value of array. in contexts, there implicit conversion char[n] char*, pointer initial (0th) element of array. this:

char *s = "hello"; 

initializes s point initial 'h' in implicitly created array object. pointer can point object; not point value. (incidentally, should const char *s, don't accidentally attempt modify string.)

string literals special case. integer literal not create object; merely yields value. this:

int *ptr = 42; // invalid 

is invalid, because there no implicit conversion of 42 int* int. this:

int *ptr = &42; // invalid 

is invalid, because & (address-of) operator can applied object (an "lvalue"), , there no object apply to.

there several ways around this; 1 should use depends on you're trying do. can allocate object:

int *ptr = malloc(sizeof *ptr); // allocation int object if (ptr == null) { /* handle error */ } 

but heap allocation can fail, , need deallocate when you're finished avoid memory leak. can declare object:

int obj = 42; int *ptr = &obj; 

you have careful object's lifetime. if obj local variable, can end dangling pointer. or, in c99 , later, can use compound literal:

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

(int){42} compound literal, similar in ways string literal. in particular, does create object, , can take object's address.

but unlike string literals, lifetime of (anonymous) object created compound literal depends on context in appears. if it's inside function definition, lifetime automatic, meaning ceases exist when leave block containing -- ordinary local variable.

that answers question in title. body of question:

what correct way use int* x?

is more general, , it's not question can answer here. there multitude of ways use pointers correctly -- , more ways use them incorrectly. book or tutorial on c , read section discusses pointers. unfortunately there lot of bad books , tutorials. question 18.10 of comp.lang.c faq starting point. (bad tutorials can identified casual use of void main(), , false assertion arrays pointers.)


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -