0

HI I am trying to understand pointers and array and while going through video on youtube I found this example which I am trying to recreate on my own. following is the code.

#include <stdio.h>
#include <math.h>
main()
{
    int arr[][2]={{11,12},{21,22},{31,32},{41,42},{51,52}};
    int i,j;
    arr[5][1]=61;
    arr[5][0]=62;
    arr[6][1]=71;
    arr[6][0]=72;
    arr[7][1]=81;
    arr[7][0]=82;
    for(i=0;i<=7;i++)
    {
        for(j=0;j<=1;j++)
        {
            printf("%d  %d  %u  %u  %d  %d  %d  \n",i,j,arr[i],arr[i]+j,arr[i][j],*(*(arr+i)+j),*(arr[i]+j));
        }
    }
}

when I execute the code it gives me

0   0   3216856768  3216856768  11  11  11  
0   1   3216856768  3216856772  12  12  12  
1   0   3216856776  3216856776  21  21  21  
1   1   3216856776  3216856780  22  22  22  
2   0   3216856784  3216856784  31  31  31  
2   1   3216856784  3216856788  32  32  32  
3   0   3216856792  3216856792  41  41  41  
3   1   3216856792  3216856796  42  42  42  
4   0   3216856800  3216856800  51  51  51  
4   1   3216856800  3216856804  52  52  52  
5   0   3216856808  3216856808  0   0   0   
5   1   3216856808  3216856812  5   5   5   
6   0   3216856816  3216856816  72  72  72  
6   1   3216856816  3216856820  71  71  71  
7   0   3216856824  3216856824  82  82  82  
7   1   3216856824  3216856828  81  81  81  

why is arr[5][0] and arr[5][1] not being assigned the given value? where is 5 and 0 coming from?

1 Answer 1

3

C ain't magic (nor a scripting language). If you create an array that has 5 elements, then it will have 5 elements. No matter what you do with it, it won't automatically expand. And later, if you access the array out of its bounds, that leads to undefined behavior. This code could even crash.

What you should do instead is either declare a large enough array:

int arr[8][2] = { { 11, 12 }, { 21, 22 }, { 31, 32 }, { 41, 42 }, { 51, 52 } };

Then later you can assign to them correctly; or use dynamically expanding arrays using the standard memory management functions malloc() and realloc():

int **arr = malloc(sizeof(*arr) * 5);
int i;
for (i = 0; i < 5; i++) {
    arr[i] = malloc(sizeof(**arr));
}

and fill it up one-by-one

arr[0][0] = 11;
arr[0][1] = 12;
// etc.

Then expand it when it's neeed:

arr = realloc(arr, sizeof(*arr) * 8);
for (i = 5; i < 8; i++) {
    arr[i] = malloc(sizeof(**arr));
}

After this, you can safely use arr[5]...arr[7] as well. In this latter case, however, don't forget to free() all pointers that need to be freed after use.

Sign up to request clarification or add additional context in comments.

1 Comment

So either define larger array or allocate memory before assigning values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.