giboo
giboo

Reputation: 103

Warning while compiling a c code - Dont know the reason

I have the following c source. But I get a warning as mentioned below

void check_func();
int var2[16][128];
int var1[][128];
int i, k;

int main()
{
    for (i = 0u; i < 16; i++)
    {
        for (k = 0u; k < 128; k++)
        {
            var2[i][k] = 4095;
        }
    }

    check_func();

    //printf("%d", var1[0]);
    return 1;
}

void check_func()
{
    var1 = &var2[0][0];
    return;
}

I get a warning when compiled in gcc.

E:\gcc-2.95.2\bin>gcc.exe check.c check.c: In function check_func': check.c:24:var1' has an incomplete type check.c: At top level: check.c:3: warning: array `var1' assumed to have one element

What is the reason for this warning and how to get rid of this? I tried type casting it to both (int (*)[]) and (void *) but still the warning persits.

i.e.

1st try:

var1 = (int (*)[])&var2[0][0];

2nd try:

var1 = (void *)&var2[0][0];

Upvotes: 0

Views: 81

Answers (1)

jamesdlin
jamesdlin

Reputation: 90155

First, let's ignore the 2D array aspect. It's not quite relevant to a fundamental misunderstanding that you have about arrays and pointers, and it adds extra complication.

With var1, you're basically attempting to declare a global variable:

int x[];

which isn't legal. Based on your comments, you seem to be under the mistaken impression that this declares a pointer, but it instead declares an array of unspecified size. As a global variable, the compiler must be able to allocate memory for this array, but that isn't possible without knowing its size.

Note that this would be different if such a declaration were used for a function parameter:

void foo(int x[]);

When used as function parameters, int x[] and int* x are interchangeable. The function does not allocate any space for the array; the array must have been allocated already, and the function instead takes a pointer to that array (or more precisely, to the array's first element).

Pointers and arrays are not the same thing. Arrays decay into pointers in certain contexts, and function parameters allow using either syntax, but they are otherwise distinct.


Based on what you're trying to do in check_func:

var1 = &var2[0][0];

you probably want to declare var1 simply as:

int* var1;
  1. var2 is a 2D array of int.
  2. Therefore var2[0][0] is of type int.
  3. Therefore &var2[0][0] is of type int*.
  4. Therefore var1 should be of type int* to match.

Upvotes: 2

Related Questions