Black Swan
Black Swan

Reputation: 853

Writing array reference using pointer arithmetic

let consider the following fragment of Code:

#include<stdio.h>
main()
{
 int count[100][10];
 *(count + (44*10)+8)=99;
 printf("%d",count[44][8]);
}

What is the wrong with it?

Upvotes: 3

Views: 81

Answers (3)

Gopi
Gopi

Reputation: 19874

count[44][8]

is not initialized and you are trying to print the value of it which is UB.

a[i][j] = *(a[i] + j); 
a[i][j] = *(*(a+i) + j);

So if you want to initialize count[44][8] then do

*(count[44] + 8) = 10; /* or *(*(count + 44) + 8) = 10 */
printf("%d",count[44][8]);

Upvotes: 2

ecatmur
ecatmur

Reputation: 157444

Array-to-pointer decay only works for one level; so int count[100][10]; decays to int (*)[100] (Why does int*[] decay into int** but not int[][]?).

You can either cast count to int* or use &count[0][0] to get an int* pointer to the first element of the 2D array.

Upvotes: 2

Mohit Jain
Mohit Jain

Reputation: 30489

*(count + (44*10)+8)=99; should be

*(count[0] + (44*10)+8)=99;

Type of countp[0] can be reinterpreted as int * as you want.

Live code here

Type of count is int [100][10] so adding some big number to it would go 10 times ahead as you want and access to that location would lead to UB.

Anopter way to write the same is:

*( *(count + 44) + 8 )=99;

Upvotes: 1

Related Questions