Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing char pointer as string vs other type pointers as arrays

Tags:

c++

c

I've got a question about initializing char pointers vs other data type pointers. Specifically, we are allowed to initialize char pointers as follows:

char *char_ptr = "Hello World";

As far as I know, the only thing special about a string is that it is a '0' terminated character array. However, we are not allowed to do the following:

int *int_ptr = {1,2,3,4};

but we must do this:

int int_arr[] = {1,2,3,4};
int_ptr = int_arr;

in order to let int_ptr point to the first element of int_array.

In the char case, we have not explicitly defined the string "Hello World" as a char array before letting char_ptr point to the string, but have initialized the char_ptr directly using the string "Hello World".

My question is, why is this the case, what is special about strings that allows us to do this but can't do so with other types?

Thanks in advance,

Sriram

like image 354
Sriram Nagaraj Avatar asked Sep 14 '25 13:09

Sriram Nagaraj


2 Answers

You can do the same in C99 or later for other types using compund literals:

#include <stdio.h>

int main(void) {
    int *ptr = (int[]){ 1, 2, 3, 4 };
    for(int i = 0; i < 4; ++i) {
        printf("%d: %d\n",i, ptr[i]);
    }
    return 0;
}

The compound literal (int[]){ 1, 2, 3, 4 } creates an unnamed int[4], just like "Hello" creates an unnamed char[6].

So as of C99, char is only special in providing a more convenient syntax.

like image 134
Daniel Fischer Avatar answered Sep 17 '25 02:09

Daniel Fischer


The answer is:

Strings(literals) are treated as special.

Believe it! Accept it, and Live with it.

like image 39
Alok Save Avatar answered Sep 17 '25 03:09

Alok Save