简体   繁体   中英

How correctly store elements in char array in C?

I am sure it's pretty obvious, but I haven't been able to figure this out for a couple hours. I need to take input (words, strings) from the user and store it in the array, and then I need to access these elements by their index or something similar.
I've tried both frets and scanf but couldn't make it work.
Here's what I have so far:

typedef struct 
{
   char components[MAX_STRING];
   int numComp;
   char weightingSheme[MAX_STRING][50];
   int numOfSchemes;
}  CourseComponents; 

char input [MAX_STRING]
CourseComponents newCourses;
int *Comp = &newCourses.numComp;
*Comp = 0;
int *numOfSchemes = &newCourses.numOfSchemes;
*numOfSchemes = 0;
for (i=0;i<newCourses.numComp;i++) 
{
    printf("Enter next component name: ");
    scanf("%s", input);
    strcpy(&newCourses.components[i], input);  
}
char components[MAX_STRING];

This only holds a "single" string. You probably want to declare it like this;

char components[MAX_ELEMS][MAX_STRING];

That's an array of strings, more precisely an array of array of chars (each string a fixed length which can be wasteful). This will get you up and running but it's not what I would call "production quality" You likely don't want hardcoded lengths like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM