0

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

Mr Habibbi
  • 31
  • 4
  • In C, 2D arrays are arrays of arrays, but you are trying to pass one as if it were an array of pointers. Your compiler ought to be warning you about the type mismatch -- pay attention to it! – John Bollinger Mar 12 '23 at 15:40

1 Answers1

1

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

0___________
  • 60,014
  • 4
  • 34
  • 74