kkmonlee kkmonlee - 1 month ago 10
C Question

Initializing n integers in 2-dimensional array

I'm having a difficult time understanding how I can initialize and add 1 to

n
integers to each element in a 2-dimensional array.

For example if
n = 5
,

arr[5][5] = { {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5} };


I have tried

for (int i = 0; i < sizeof(arr); i++) {
for (int j = 0; j < sizeof(arr[i]); j++) {
product[i][j] += 1;
}
}

Answer

This should give you a starting point:

#include <stdio.h>
#include <stdlib.h>

#define LENGTH 5

int main(int argc, char** argv) {
    int arr[LENGTH][LENGTH] = { { 0 } };
    for (int i = 0; i < LENGTH; i++) {
        fprintf(stderr, "%p contains %d elements\n", (void *) arr[i], (int) sizeof(arr)/sizeof(*arr));
        for (int j = 0; j < LENGTH; j++) {
            arr[i][j]++;
            fprintf(stderr, "%d ", arr[i][j]);
        }
        fprintf(stderr, "\n");
    }
    return EXIT_SUCCESS;
}

Note that you can only do the sizeof(foo)/sizeof(*foo) trick because foo is on the stack. You can't do this with dynamically allocated memory via pointers.