Skip to main content
2 of 4
added 1 character in body
kzidane
  • 17.7k
  • 3
  • 28
  • 100

I don't think this is the question you should ask since you could simply have an answer to it by opening up a text editor, writing the code you want and then try to compile it see if it compiles or not.

What you should ask is why it doesn't work.

Let's agree that char arrays (strings) are used extensively in C programs. That's one reason why the language implementations made it possible to create strings in various ways, one of which is the one you've shown in your question

char *str = "foo";

The value "foo" is often referred to as a string literal. It's a constant value (aka a compile-time constant), which means that you can't modify it later on (or you'd get a compile-time error).

The whole statement basically creates an array of chars, namely str by allocating memory for exactly 4 characters (3 characters + the null character) on a data segment in memory.

Array names decay to pointers (i.e., if you used the name of an array by itself, then you're using a pointer to the whole array which happens to be also a pointer to the first element in the array). So str here is mainly a pointer to the whole array, but it also could be a pointer to the first element in the array (i.e., the char 'f' in this case).

Imagine how you'd create a string without this syntactic sugar. Typically, you'd do something like

// notice the curly braces (NOT square brackets as you used)
char str[] = {'f', 'o', 'o', '\0'}; 

Or

char str[4];
str[0] = 'f';
str[1] = 'o';
str[2] = 'o';
str[3] = '\0';

Syntactic sugar makes the language sweeter by providing easier and quicker ways to do more complicated things.

NOTICE though that you'd be able to modify the contents of the string in the second and third examples because these wouldn't be constant strings as the string literal. To be honest, there are situations where you have to create a string in one of these ways to be able to modify the string's contents.

For integers (or pretty much any other type), on the other hand, this definitely won't work because

  1. you're trying to create an array using square brackets which is syntactically wrong.

  2. you're trying to assign an array to a pointer which won't type-check (because pointers store memory addresses not arrays).

The closest thing you create an int array that easy is probably using a way that is similar to the second way above

int arr[] = {1, 2, 3};

NOTICE that initializing an array with an initializer-list has to be done on the same statement as you declare the array.

If you want to create an int array on the heap, then probably the easiest way to do it is

int *arr = malloc(3 * sizeof(int));
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;

In this particular case, you could alternatively use a for loop

for (int i = 0; i < 3; i++)
    arr[i] = i;
kzidane
  • 17.7k
  • 3
  • 28
  • 100