简体   繁体   中英

I am trying to assign a string value to an array of character arrays

I am trying to assign a string value (char *) to an element in an array of char arrays. My problem is, I can do the assignment, but it places the last read value into every element, instead of the specific element I wanted. My code looks as follows.

int   wordListIterator = 0;

int main(int argc, char **argv) {

    FILE *fp = fopen(argv[1], "r");

    int lineCount = 0;

    char line[80];
    while (fgets(line, sizeof(line), fp) != 0) {
    parseLine(line, strlen(line), lineCount);
    lineCount++;
    }
    fclose(fp);
} // end main

void parseLine(char * myLine, int stringLength, int myLineCount) {

    if (isspace(myLine[1])) {
        int i;
    for (i = 0; i < stringLength; i++) {
        Puzzle[myLineCount][i] = myLine[i];
    }

} else
if (isspace(myLine[1]) == 0) {
     Wordlist[wordListIterator] = myLine;
    wordListIterator++;
}
}

My output will have Wordlist[] be full of the last word read. This is for a word search puzzle. The Puzzle[][] assignment works great, so I do not understand where I am going wrong.

You need to use strdup to copy your line, otherwise your going to overwrite the line every time, and every single one of your values is going to be a pointer to the same string. That string is going to contain the last input, so all of them are going to be pointing to the last input.

Your "puzzle" assignment works alright because you're copying the actual characters over one at a time.

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