Christian Halim
Christian Halim

Reputation: 117

How do you pass 2-dimensional array of character into a function?

So i'm trying to pass

char parent[n][50];

into a function initialize();
And then copy the char x, into the parent [ i ] inside the initialize(); function. Example

x = "Cityname"
and when passed into the initialize();
it would do
strcpy(parent[i], x);
to make the
parent[i] = "Cityname"
void initialize(char *parent, int *ranks, char x, int i){

    strcpy(parent[i], x);
    ranks[i] = '0';

}

int main(){

    int n, i = 1;
    char x[20];

    printf("Enter how many city are there : "); scanf("%d", &n); fflush(stdin);

    char parent[n][20];
    int ranks[n];

    while(1){
        printf("enter city name: "); scanf("%[^\n]", x);
        if(i <= n){
            initialize(parent[][20], ranks, x, i);
            i++;
        } else {
            printf("The city is at maximum\n");
        }
    }
}

It tells a warning:

passing argument 1 of 'strcpy' makes pointer from integer without a cast 
note: expected 'char *' but argument is of type 'char' 
and also in function main 
error: expected expression before ']' token

Can anyone explain how to strcpy(parent[i], x) correctly? I can't seem to figure this problem out.

Upvotes: 0

Views: 34

Answers (1)

Program man
Program man

Reputation: 393

I see several problems with your code. Arrays vs pointers in C can be confusing, so there are a few rules to keep in mind:

char x[n] can be automatically converted by the C compiler to char *x.

char x[10][20] is represented under the hood as a 1D array, and the compiler computes the offsets behind the scenes. For example, if x were a 10 x 20 array, the expression x[1][2] could be compiled as *(x + 22). For this reason, it can cause surprising results to cast a 2D array to a char*, and it is invalid to cast a 2D array to a char**.

With these rules in mind, here is how I would change your code

void initialize(char (*parent)[20], int *ranks, char *x, int i){

    strcpy(parent[i], x);
    ranks[i] = '0'; // Did you want an automatic conversion from char to int here? Maybe you meant ranks[i] = 0?

}

int main(){

    int n, i = 0; // As Craig mentions, i should start at 0.
    char x[20];

    printf("Enter how many city are there : "); scanf("%d", &n); fflush(stdin);

    char parent[n][20];
    int ranks[n];

    while(1){
        printf("enter city name: "); scanf("%19s", x); // scanf will automatically stop at whitespace, and you must include the max length to avoid a buffer overrun.
        if(i < n){
            initialize(parent, ranks, x, i);
            i++;
        } else {
            printf("The city is at maximum\n");
            // Maybe break here, unless you want an infinite loop
        }
    }
}

Upvotes: 2

Related Questions