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%s\n", s);
printf("%c", s[2]);
}
int main()
{
char mystr[5] = "Hello";
printf("%s\n", mystr);
printf("%c\n", mystr[4]);
mystring();
}
int i = 0;
perhaps this scope is wrong