3

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Black Swan
  • 813
  • 13
  • 35

3 Answers3

2
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]);
Gopi
  • 19,784
  • 4
  • 24
  • 36
  • Would U please explain ur code...! is it a rule a[i][j] = *(a[i] + j); a[i][j] = *(*(a+i) + j) for accessing 2d array @Gopi – Black Swan Jan 29 '15 at 12:16
  • int count[100][10],*countP; countP=count; *(countP[44]+8)=99; it is not working for this fragment. – Black Swan Jan 29 '15 at 12:27
  • @BlackSwan - that is the rule. Any array is simply a block of addresses in memory. You can address any specific address with either normal array notation `count[44][8]` or by specifying the `offset` in memory from the base address of count (e.g. `*(*(count + 44) + 8)`). The basic equivalence is easier understood for a 1D array: `a[i] = *(a + i)`. For a 2D array, you simply have an additional layer: `a[i][j] = *(*(a + i) + j)` – David C. Rankin Mar 27 '15 at 06:08
2

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.

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • i am not familiar c++, only with C. it worked in ur way, but i am still confused that why i have to cast it...! – Black Swan Jan 29 '15 at 12:02
  • @BlackSwan see Oliver Charlesworth's answer: http://stackoverflow.com/a/14183554/567292 - array-to-pointer decay works exactly the same in C and C++, it's just that C++ gives more ways to observe it. – ecatmur Jan 29 '15 at 12:04
1

*(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;
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100