Grieverheart
Grieverheart

Reputation: 510

Pointers to columns of 2D array

I have an NxN 2D array implemented as a 1D array using A[N*i+j]. I want to make references to the columns of the array and be able to pass them to functions as regular column vectors. You can see an example below for N=3. The function returns just the square of the vector passed to it:

#include <stdio.h>

int func(int* vec[3]){
    int result=0;
    for(int i=0;i<3;i++){
        result+=(*vec[i])*(*vec[i]);
        printf("vec[%d]=%d\n",i,*vec[i]);
    }
    return result;
}

void main(){
    int A[]={0,1,2,3,4,5,6,7,8};

    int *a[3][3];

    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            a[j][i]=&A[3*i+j];
        }
    }
    for(int i=0;i<3;i++){
        printf("vector %d\n",i);
        for(int j=0;j<3;j++){
            printf("%d\n",*a[i][j]);
        }
    }

    printf("%d\n",func(a[0]));
}

This works but the problem is the function works only for arguments of type int* vec[3]. What I would really like is to have the function taking an argument of type int vec[3] but I'm confused on how I should then pass the vector of pointers as a vector of the values the vector elements point to.

Upvotes: 1

Views: 1833

Answers (3)

Glenn
Glenn

Reputation: 1167

C is row based for accessing elements, so you can pass the address of a row, but to get the values for the columns, you would have to pass the whole matrix and then access the matrix using the row and column indexes, or do the computation yourself to get the correct elements if you just pass the address of the matrix (you would also have to pass the number of columns and possibly rows for the computation to determine the location of the element).

Upvotes: 0

Travis Webb
Travis Webb

Reputation: 15018

In C, you cannot pass arrays as arguments, or return them from functions. You can only pass pointers like you are currently doing. vector is an STL class in C++, which you are using interchangeably and confusingly with array. You can pass a pointer which could reference the first element in a column in a real 2D array, but not for a ni+j array.

Upvotes: 0

anirudh
anirudh

Reputation: 562

It is not possible to do what you want, atleast not in C.

Upvotes: 3

Related Questions