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;
}