Home > other >  Save mutliple strings of variable length in a single array in C
Save mutliple strings of variable length in a single array in C

Time:11-06

I'm trying to make a QnA game that will take 5 random questions from a pool of 10 and print them to let the user answer. I have a 2D array to save 10 strings that will be the questions. My work so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void qna(){
    int i;
    
    char er[10][13]; //10 questions
    
    er[0][]="2 2"; //ans 4
    er[1][]="4-5"; //ans -1
    er[2][]="10*10"; //ans 100
    er[3][]="17*3"; //ans 51
    er[4][]="9/3"; //ans 3
    er[5][]="45 24 35-68"; //ans 36
    er[6][]="4-2"; //ans 2
    er[7][]="592-591"; //ans 1
    er[8][]="8 3"; //ans 11
    er[9][]="9*9"; //answer 81
    
    for(i = 0; i < 10; i  ){ //test to see if strings save correctly
        printf("%s\n", er[i]);
    }
    
}

int main() 
{
    qna();
    return 0;
    
}

When I compile the program, I get an error "[Error] expected expression before ']' token" for every line that assigns a string to er. Then I tried this:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void qna(){
    int i;
    
    char er[10][13]; //10 questions
    
    er[0][13]="2 2"; //ans 4
    er[1][13]="4-5"; //ans -1
    er[2][13]="10*10"; //ans 100
    er[3][13]="17*3"; //ans 51
    er[4][13]="9/3"; //ans 3
    er[5][13]="45 24 35-68"; //ans 36
    er[6][13]="4-2"; //ans 2
    er[7][13]="592-591"; //ans 1
    er[8][13]="8 3"; //ans 11
    er[9][13]="9*9"; //answer 81
    
    for(i = 0; i < 10; i  ){ //test to see if strings save correctly
        printf("%s\n", er[i]);
    }
    
}

int main() 
{
    qna();
    return 0;
    
}

When I run this I get a warning "[Warning] assignment makes integer from pointer without a cast" instead of an error on the same lines as before. The command line window prints weird symbols instead of the strings, and some lines are blank entirely. How do I fix this?

CodePudding user response:

Since you don't seem to be changing the contents of any of these strings, you can use an array of pointers to (read-only) strings in memory:

char* er[] = {
    "2 2", //ans 4
    "4-5", //ans -1
    "10*10", //ans 100
    "17*3", //ans 51
    "9/3", //ans 3
    "45 24 35-68", //ans 36
    "4-2", //ans 2
    "592-591", //ans 1
    "8 3", //ans 11
    "9*9" //answer 81
};

CodePudding user response:

Use strcpy to copy the strings into the buffer.

strcpy(er[0], "2 2");
strcpy(er[1], "4-5");
//etc.

or just initialize at creation:

char er[10][13] = {
   "2 2",
   //...
};
  • Related