I´ve just seen multidimensional arrays and as practice I first wanted to print out a string with this code; alas it didn´t work.
#include <stdio.h>
main()
{
char a[][20] = {"Hello"};
printf("%s" , a [1]);
getchar();
}
The only way I managed doing this was with a adding each character with a loop:
#include <stdio.h>
main()
{
char a[] = {"Hello"};
int i=0
while(a[i]!='\0')
{
printf("%c" , a[i]);
i++;
}
getchar();
}
What am I missing when initialising the string?
In the first fragment, you are accessing memory that’s out of bounds. The code that would work is:
C arrays are indexed from zero. You only defined and initialized
a[0]; therefore, accessinga[1]is undefined behaviour.In your second example, you could use
"%s"OK:Or you could use:
This is, of course, a single dimensional array.