Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer initialization in C

Tags:

In C why is it legal to do

char * str = "Hello"; 

but illegal to do

int * arr = {0,1,2,3}; 
like image 952
Bruce Avatar asked Oct 02 '11 17:10

Bruce


People also ask

How is pointer initialized in C?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.

What is the syntax for initialization of pointer?

General syntax of pointer declaration is, datatype *pointer_name; Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing.

Can we initialize a pointer in C?

& is a reference operator which means it is used to get the memory location of the variable. So 'a' is an integer variable and by doing &a, we are getting the location where a is stored in the memory and then letting the pointer point to that location. This is the first method of initializing a pointer in C.

What is pointer initialization value?

Value-initialization of a pointer initializes it to a null pointer value; therefore both initializer lists are equivalent. To zero-initialize an object or reference of type T means: if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T.


2 Answers

I guess that's just how initializers work in C. However, you can do:

int *v = (int[]){1, 2, 3}; /* C99. */ 
like image 122
cnicutar Avatar answered Oct 14 '22 11:10

cnicutar


As for C89:

"A string", when used outside char array initialization, is a string literal; the standard says that when you use a string literal it's as if you created a global char array initialized to that value and wrote its name instead of the literal (there's also the additional restriction that any attempt to modify a string literal results in undefined behavior). In your code you are initializing a char * with a string literal, which decays to a char pointer and everything works fine.

However, if you use a string literal to initialize a char array, several magic rules get in action, so it is no longer "as if an array ... etc" (which would not work in array initialization), but it's just a nice way to tell the compiler how the array should be initialized.

The {1, 2, 3} way to initialize arrays keeps just this semantic: it's only for initialization of array, it's not an "array literal".

like image 38
Matteo Italia Avatar answered Oct 14 '22 12:10

Matteo Italia