printing strings populated with a loop in C?
I'm new to C and trying to learn about printing strings and single elements of arrays.
In the main function I have created a char array of 5 characters and am able to print the string. I am also able to print 1 element of the array. This all works fine.
I have then created a function which has a for loop to populate an array with 26 available slots and want to do the same thing, print the whole string and then just print a single element of it.
When my program executes it should print: Hello o ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ (This should print twice, once for the for loop and then once when I try to print the string) C
However when I try to print the characters this time, I am running into errors and the only difference I can see is the way I have initialised the array. I don't understand the difference and why it is breaking. Is it something to do with the scope of the for loop? I also tried making the char array static but that didn't work either. Can anyone help with this?
Here's my code
I'm new to C and trying to learn about printing strings and single elements of arrays.
In the main function I have created a char array of 5 characters and am able to print the string. I am also able to print 1 element of the array. This all works fine.
I have then created a function which has a for loop to populate an array with 26 available slots and want to do the same thing, print the whole string and then just print a single element of it.
When my program executes it should print: Hello o ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ (This should print twice, once for the for loop and then once when I try to print the string) C
However when I try to print the characters this time, I am running into errors and the only difference I can see is the way I have initialised the array. I don't understand the difference and why it is breaking. Is it something to do with the scope of the for loop? I also tried making the char array static but that didn't work either. Can anyone help with this?
void mystring()
{
char s[26];
for(char ch = 'A'; ch < 'Z'; ch++)
{
int i = 0;
s[i] = ch;
printf("%c", s[i]);
i++;
}
printf("n%sn", s);
printf("%c", s[2]);
}
int main()
{
char mystr[5] = "Hello";
printf("%sn", mystr);
printf("%cn", mystr[4]);
mystring();
}
There is no null
terminator for both your "strings", I write "strings" because they are in effect NOT strings according to the definition of string in c.
Your i
variable is always 0
, just use a simple formula ch - 'A'
will give the correct index.
Your char mystr[5] = "hello";
has insufficient space, you need to allocate space for the terminating '