Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading