vipil
vipil

Reputation: 85

3d array using pointers

I am new to C programming. Currently am trying to learn 3d array using pointers. Below is a program I am trying to debug. Can any one explain the difference between the two programs given below?

code1:

#include <stdio.h>
int main()
{
    int a;
    int d[2][2][2] = {1, -2, -3, 0, -9, -1, 3, -1};
    printf("%d\n",*(*(*(d +1)+1)+1));
    if(*(*(*(d +1)+1)+1) <(a= sizeof( int )))
        puts(" u got it ");
    else
        puts (" but wrong");
    return 0;
}

code2:

#include <stdio.h>
int main()
{
    int a;
    int d[2][2][2] = {1, -2, -3, 0, -9, -1, 3, -1};
    if(*(*(*(d +1)+1)+1) <(sizeof( int )))
        puts(" u got it ");
    else
        puts (" but wrong");
    return 0;
}

In the first code I am getting the […incomplete…]

Upvotes: 0

Views: 180

Answers (2)

Nandyy
Nandyy

Reputation: 161

It is basically an integer type comparison problem. First program compares a signed int(-1) with a signed int(a) and the second, a signed int(-1) with an unsigned int(sizeof()). Integer promotion happens in the second case, where signed int(-1) gets converted to unsigned int(-1) -> SIZE_MAX. For more details on type comparison check the thread, What are the general rules for comparing different data types in C?

Upvotes: 1

M.M
M.M

Reputation: 141648

int d[2][2][2] = {1, -2, -3, 0, -9, -1, 3, -1};

The initializer is not fully braced but in this situation the initializers apply to the next element of the array in memory, so this assigns d[0][0][0] = 1, d[0][0][1] = -2, d[0][1][0] = -3, etc.

printf("%d\n",*(*(*(d +1)+1)+1));

The thing full of stars is an obfuscated way of writing d[1][1][1] . The definition of X[Y] is *(X+Y) .

(a= sizeof( int )))

The type of an assignment expression is the type of the left-hand operand. So the first program does (int)-1 < (int)4 . The second program does (int)-1 < (size_t)4 . (assuming your ints are 4 bytes big).

In the first case this is true. In the second case it is a type mismatch. The type mismatch has to be fixed before the comparison can occur. The rules of C say that in this case the signed type is converted to the unsigned type, giving (size_t)-1 < (size_t)4. Since (size_t)-1 is actually the largest possible size_t value, this comparison is false.

Upvotes: 4

Related Questions