1

Iterating through a fixed-length string is easy, but when a variable-length string is used, the iteration fails after 0-th index.

For example, in the code below (printing characters of a string p one-by-one), using p[] doesn't work, while p[some integer] work (but we don't always know what that some integer is).

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    setbuf(stdout, NULL);

    // variable p to store string
    // if you change the line to let's say char p[20]=""; it will work
    char p[]="";
    printf("Enter a string: ");
    scanf("%s", p);

    printf("You entered: %s\n", p);
    printf("String length: %d\n", strlen(p));

    printf("Printing each character of the string:\n");
    int i=0;
    while (p[i] != '\0')
    {
        printf("p[%d] is %c\n", i, p[i]);
        i++;
    }

    return 0;
}
Tan En De
  • 331
  • 1
  • 3
  • 13
  • 3
    Does this answer your question? [How can I read an input string of unknown length?](https://stackoverflow.com/questions/16870485/how-can-i-read-an-input-string-of-unknown-length) – UnholySheep Mar 01 '20 at 14:38
  • 1
    Besides the buffer overflow: https://stackoverflow.com/questions/12306591/read-no-more-than-size-of-string-with-scanf - so even with `char p[20]` you would need `%19s` in the `scanf` to be safe. – tevemadar Mar 01 '20 at 14:44

2 Answers2

3

When an array is not given an initial size, it is made exactly large enough to hold what it is initialized with. In this case, you initialize a char array with the empty string "". This string constant consists of a single null byte, so p is an array of size 1.

Then when you attempt to read a string into it you write past the end of the array, invoking undefined behavior.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

If we omit the array dimension, compiler computes it for us based on the size of initialiser.

In this statement:

char p[]="";

the initialiser is an empty string literal (string literal with only a '\0' character). So, the size of char array p will be 1.
Accessing an array beyond its size is undefined behavior. An undefined behavior includes it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.

H.S.
  • 11,654
  • 2
  • 15
  • 32