I find strings or character arrays in C confusing, so I tend to make mistakes and errors while writing code. The below code takes in a character array and while printing, prints the fourth element as x.
void printString(char stuff[]) {
for (int i = 0; i < 5; i++) {
if (i == 3) {
stuff[i] = 'x';
}
printf("%c", stuff[i]);
}
}
int main(void) {
char z[] = "hello";
printString(z); // output helxo
When trying to apply the same concept with an array of character arrays, you can't change the values
void printStrings(char stuff[5][20]) {
for (int i = 0; i < 5; i++) {
if (i == 4) {
stuff[i] = "Not Cool"; // Error: assignment to expression with array type
}
printf("%s\n", stuff[i]);
}
}
int main(void) {
char a[5][20] = {
"Words",
"More Words",
"Letters",
"Arrays",
"Cool"
}
}
Any help would be appreciated.
P.S. Any links to a resource explaining character arrays and strings would also be helpful :)