1

I have this code,

char a[0];
cout << "What is a? " << a << endl;
char *word = itoa(123,a,10);
string yr = string(word);

but i have trouble comprehending the array a[0]. I tried to change its value and see if there is any changes, but it seems to make no differences at all.

example, even if a change a[0] to a[1], or any other integer, the output still make no difference

char a[1];
cout << "What is a? " << a << endl;
char *word = itoa(123,a,10);
string yr = string(word);

What is its purpose here?

dee cue
  • 983
  • 1
  • 7
  • 23

2 Answers2

3

Since itoa function is non-standard, this is a discussion of a popular signature itoa(int, char*, int).

Second parameter represents a buffer into which a null-terminated string representing the value is copied. It must provide enough space for the entire string: in your case, that is "123", which takes four characters. Your code passes a[] as the buffer, but the size of a[] is insufficient to accommodate the entire "123" string. Hence, the call causes undefined behavior.

You need to make a large enough to fit the destination string. Passing a buffer of size 12 is sufficient to accommodate the longest decimal number that can be produced by itoa on a 32-bit system (i.e. -2147483648). Replace char a[0] with char a[12] in the declaration.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

What is its purpose here?

A zero-length array is an array with no elements in it.

You can't [legally] print or modify its contents, because it doesn't have any.

There are arcane reasons to want to use one, but speaking generally it has no purpose for you. It's not even allowed by the standard (although compilers tend to support it for those arcane reasons).

even if a change a[0] to a[1], or any other integer, the output still make no difference

Well, if you have an array with n elements in it, and you write more than n elements' worth of data to it, that's a "buffer overrun" and has undefined behaviour. It could appear to work as you overwrite somebody else's memory, or your program could crash, or your dog could suddenly turn into a zombie and eat you alive. Best avoided tbh.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055