char pointer vs int pointers

Hey,
I have a problem with 'int pointers' vs 'char pointers'.
Let's see a simple exemple:
1
2
  char* x = "test"; //ok
  int* a = 12;// not ok 


In the "char" example above if i don't use new or malloc for "x" is returned an address. How return this address? And why this doesn't work the same for int?

If i want to work this for "int" i need to do something like this :
 
int* a = new int(10);

It doesn't work if i don't allocate memory with new or malloc.
Thx.
If you try to assign a character literal to a char* it will fail to compile for the same reason as your int* example did.
 
char* x = 't'; // not ok 


In many situations arrays implicitly decay to pointers to the first element in the array.
1
2
3
4
char charArray[] = {'A', 'B', 'C'};
char* x = charArray; // ok, x points to the first element in charArray ('A')
int intArray[] = {1, 2, 3};
int* y = intArray; // ok, y points to the first element in intArray (1) 


A string literal gives you an array of characters so it implicitly decays to a pointer the same way as above. String literals are read-only so modern compilers will complain if you don't use const.
 
const char* x = "test"; //ok 
Last edited on
Very nice, i understand the problem.
Thank you very much @Peter87.
Topic archived. No new replies allowed.