如何从c中的引用为2d数组赋值? [英] How to assign value to a 2d array from reference in c?

查看:65
本文介绍了如何从c中的引用为2d数组赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int max(int x,int y){
if(x>=y)
 return x;
else
 return y;
             }
int calci(int i,int j,int n,int *c){
int k,y,m;
k=j;
y = (n)/((2^i)*(2^j));
for(y=i;y>=0;y--){
for(k=j;k>=0;k--){
 *(*(c+2)+k) = max(y,calci(i+1,k,n,c)+calci(i+2,k,n,c)+calci(i,k+1,n,c));   
    }
 for(y=0;y<=j+2;y++){
 *(*(c+1)+y)=*(*(c+2)+y);
*(*(c+0)+y)=*(*(c+1)+y);
}
}
 return *(*(c+2)+0);
 }


int main(){
int i,j,n,z,x,y;
printf("Enter the amount\n");
scanf("%d",&n);
x=log(n)/log(2);
y=log(n)/log(3);
int arr[3][y+3];
for(i=0;i<=2;i++)
for(j=0;j<=y;j++)
arr[i][j+2]=0;
z = calci(x,y,n,arr);
printf("\n%d",z);
}

在这里,我得到错误,因为一元'*'(具有'int')的无效类型参数.我实际上是在尝试将max函数返回的值分配为第2行和第k列的数组元素.

Here I get error as invalid type argument of unary '*' (have 'int'). I am actually trying to assign the value returned by max function as array element of row 2 and column k.

推荐答案

您正在对一星指针执行两次取消引用.您尝试将其视为数组数组,但是您要传递的是一个衰减到指针的2D数组. 2D数组是单个连续的内存块,可以使用算术进行寻址以计算所需的单元格.对于N x M矩阵,如果需要元素[w] [x],则可以执行arr [N * w + x].或使用现代C标准,您可以将函数签名调整为像这样,并像往常一样访问数组:

You are performing two dereferences on a one-star pointer. What you are attempting to do is treat it as an array of arrays, but what you are passing in is a 2D array that decays to a pointer. A 2D array is a single contiguous block of memory that can be address with arithmetic to calculate the cell you want. For an N x M matrix, if you want element [w][x], you can do arr[N*w + x]. Or with a modern C standard, you can adjust your function signature to be like this and access the array as normal:

int calci(int i, int j, int n, c[i][j])

这篇关于如何从c中的引用为2d数组赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆