I am working through a textbook teaching myself C programming using the Code::Blocks v20.03 IDE.
I am really bamboozled by a small program that is to read in three small strings into a 2d char array and then just print them out to the screen. The code for the program is shown below.
#include <stdio.h>
int main(void)
{
char *colors[3][10] = {'\0'};
printf("\nEnter 3 colors seperated by spaces: ");
scanf("%s %s %s", colors[0][0], colors[1][0], colors[2][0]);
printf("\nYour entered: ");
printf("%s %s %s\n", colors[0][0], colors[1][0], colors[2][0]);
return 0;
}
This compiles with zero errors or warnings and when executed produces the following output.
You entered: (null) (null) (null)
Using the IDE's Watches window shows that nothing is written to the array. I understand that an array name is treated as a pointer to the first element in the array. I also understand the use of subscripts/indexes to access elements within the dimensions of the array (e.g. arrays of ints) and so the need to keep the array second dimension at zero in this char array.
Sadly, this has me completely foxxed and so I need help to fill in my gap in understanding.
Best regards,
Stuart
colors[0][0]
is a pointer. But it's a null pointer. It can't be used forscanf
(orprintf
). I suspect you really wantchar colors[3][10];
(note that there's no*
). And then pass onlycolors[0]
(etc) to bothscanf
andprintf
."%s"
. Always restrict it with a width specifier. eg, ifb
points to an array of size N, use a modifier of size N - 1. egchar b[32]; scanf("%31s", b);
. Rather than hard coding the width, you may wish to construct the format string withsprintf
or similar.