Declan Fitzpatrick
Declan Fitzpatrick

Reputation: 160

Copy array of strings into another array in C

I'm making a word search program in C which takes the user input and then chooses one of the global arrays of words and uses that to generate the word search. It works when I just use one of the global arrays but not with the choice, I want to copy the contents of the category arrays, depending on the users choice into the newArray which can be used with the word search. The program crashes after entering an option at the moment, here's what I have.

switch(choice)
{
    case 1: choseArray(newArray, massEffect);
    break;
    case 2: choseArray(newArray, fallout3);
    break;
    case 3: choseArray(newArray, elderScrolls);
    break;
    case 4: choseArray(newArray, gameOfThrones);
    break;
    case 5: choseArray(newArray, breakingBad);
    break;
    default: printf("Enter a valid option!");
}

void choseArray(char** newArray, char** category)
{
     int i;
     for(i=0;i<6;i++)
     {
         strcpy(newArray[i], category[i]);
     }
}

The arrays look like this and are declared globally for now

char gameOfThrones[6][250] = {"KINGSLANDING", "TYRIAN", "STARK", "LANISTERS", "WESTEROS", "WINTERFELL"};
char breakingBad[6][250] = {"JESSE", "WALT", "HEISENBERG", "SAUL", "GUSTAVO", "BREAKFAST"};
char newArray[6][250];

Upvotes: 4

Views: 16813

Answers (2)

John Bollinger
John Bollinger

Reputation: 180286

If you declare your word lists in this form ...

char gameOfThrones[6][250] = { ... };

then they are arrays of arrays of chars. The function parameter type char ** is a pointer to a char pointer, which is not even directly comparable. Your compiler should have thrown a fit about this.

Supposing that newArray is of the same type as the base word lists, you should declare your function like so:

void choseArray(char newArray[][250], char category[][250]) { ... }

... or possibly like so:

void choseArray(char (*newArray)[250], char (*category)[250]) { ... }

... to match the actual argument types. The body of your function probably works as-is in that case.

Upvotes: 2

Weather Vane
Weather Vane

Reputation: 34585

Didn't you get a compiler warning? Try declaring the function to match the arguments passed.

#include <stdio.h>
#include <string.h>

void choseArray(char newArray[][250], char category[][250]){
    int i;
    for(i=0;i<6;i++)
        strcpy(newArray[i], category[i]);
}

int main()
{
    char gameOfThrones[6][250] = {"KINGSLANDING", "TYRIAN", "STARK", "LANISTERS", "WESTEROS", "WINTERFELL"};
    char breakingBad[6][250] = {"JESSE", "WALT", "HEISENBERG", "SAUL", "GUSTAVO", "BREAKFAST"};
    char newArray[6][250];
    choseArray(newArray, gameOfThrones);
    return 0;
}

The way you were doing it

char **newArray

is a pointer to a pointer, or, an array of pointers.

Upvotes: 3

Related Questions