1

I saw this code in the lecture

char array[1000] = "";

and it was going to put the string afterwards in this array, so I understand that it's like a forward declaration of the array.

But why not write

char array[1000];

and write like the one above?

What's the difference between the two codes and what would be the function of the prior code?

hyun
  • 55
  • 8
  • 1
    You might find [C char array initialization](https://stackoverflow.com/a/18689205/1115360) informative. – Andrew Morton Feb 09 '21 at 13:07
  • 1
    Depends on if you intend to use the array without filling it up first or not. In beginner classes, teachers tend to want you to always initialize every variable you write, to save you from numerous common beginner bugs (using variables that were never initialized). – Lundin Feb 09 '21 at 13:08
  • You need to read the C book. Object initialization is described in any of them. – 0___________ Feb 09 '21 at 13:32

3 Answers3

1

The first version, i.e. char array[1000] = "";, makes an array of 1000 chars and then turns it into the empty string, i.e. the array for which the first element is the string terminator '\0'. The second version just makes the array but doesn't assign anything.

The first definition is a valid definition of a string. You can for example feed it to printf (although the output won't be very exciting). The second definition may or may not be a valid definition of a string, depending on whether or not one of the 1000 entries in the array happens to be '\0'. You don't know. And if there by chance are no '\0's in array, then treating it as a string is undefined behavior.

gspr
  • 11,144
  • 3
  • 41
  • 74
1
char array[1000] = "";

is equivalent to

char array[1000] = { '\0' }; // zero length string

Moreover

T t[1000] = { N };

is equivalent to

T t[1000] = { N, 0, 0, 0 ..., 0 ,0 }; // filled up to 1000 elements with zeros

So in your case, the first array is initialised with 1000 zeros and the second one contains 1000 uninitialised chars.

If your intention is to immediately initialise the content with something else, then the second case could be accepted.

char array[1000]; // not initialised yet
sprintf(array, "%d %s", an_integer, a_string); // now it is

Otherwise, if you expect the array to be read immediately, it is safe to initialise it immediately too.

char array[1000] = "";         // the string in array must be terminated
strcat(array, " append this"); // in order to append something
prog-fh
  • 13,492
  • 1
  • 15
  • 30
1

Both ways work just fine compiler-wise.

But in the first case, where the empty string is assigned, it is removing the "trash" data contained in the array and setting it as an empty array.

I don't have the context of the rest of the code. But it could be important that it started as an empty string other than just random data.

Baldo
  • 26
  • 4