2D array being iterated after being declared through parameters vs as a variable

Advertisements

I am having trouble iterating through a 2D array when the array is being called through the parameters of a function.

The problem is that when being run directly in main it can print out the array perfectly, but when called from func() it outputs an empty result.

2D array called from parameters:

void func(char *arr[]) {
    for (int i = 0; i < 3; i++) {
        printf("%s", arr[i]);
    }
}

int main() {
    char arr[3][5] = {"B10","A12", "D21"};
    func(arr);
    
    return 0;
}

2D array being iterated directly:

int main() {
    char arr[3][5] = {"B10","A12", "D21"};

    for (int i = 0; i < 3; i++){
        printf("%s", arr[i]);
    }

    return 0;
}

Expected output for both:
B10A12D21

>Solution :

char *arr[] is not the same as arr[3][5] as it is an array of pointers to char. The latter is a 3 element array of array of 5 characters.

You need to declare the parameter as an pointer to an array of 5 char elements.

void func(char (*arr)[5]) {
    for (int i = 0; i < 3; i++) {
        printf("%s\n", arr[i]);
    }
}

https://godbolt.org/z/Gfv8e739n

or change the type of the array in the main function.

void func(char *arr[]) {
    for (int i = 0; i < 3; i++) {
        printf("%s\n", arr[i]);
    }
}

int main() {
    char *arr[] = {"B10","A12", "D21"};
    func(arr);
    
    return 0;
}

https://godbolt.org/z/MY8Kj4faj

Leave a ReplyCancel reply