简体   繁体   中英

why can't we access 2D array as of 1D array? How can i access?

Why can't we access a 2D array as of 1D array? How can I access?

Array function:

int **combination(int no)
{

int i,j,c=0;
static int arr[100][2];

for(i=0;i<=no;i++){
    for(j=0;j<=no;j++){
        if(((i+j)==no)){
            arr[c][0]=i;
            arr[c][1]=j;
            c++;
            }
    }
}

return arr;
}

Main function:

int main() {
    int n,k,i;
    int **arr;
    int size=10;//let us assume.

    scanf("%d %d", &n, &k);
    fprintf(stderr, "1\n");
    arr=combination(n);
    fprintf(stderr, "2\n");

    for(i=0;i<size;i++){
    printf("%d-%d",arr[i][0],arr[i][1]);
}
    return 0;
}

It is showing:

.c:29:8: warning: return from incompatible pointer type [-Wincompatible-pointer-types] return arr

and segmentation fault core dumped.

Can you suggest what is the pointer type to call to access the element from that 2D array?

That is because int arr[100][2] ( a pointer to array of int [2] ) is not compatible with int** ( a pointer to pointer to int ).

Why?

C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)

Array pointer conversion

(p3) Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary '&' operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue.

Applying 6.3.2.1(p3) to int arr[100][2] , the result is int (*arr)[2] ( a pointer to array of int [2] ) which is not int** . So your compiler properly generates the warning.

If you really want to do it this way, then in main() change your declaration of arr to:

    int (*arr)[2];

And then change your function declaration to:

int (*(combination)(int no))[2]

(a function taking (int no) returning int (*...)[2] a pointer to array of int [2] )

You should also limit the value of c in your function to less than 100 to prevent exceeding your array bounds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM