gpt4 book ai didi

创建一个以运行时尺寸作为输入的矩阵

转载 作者:行者123 更新时间:2023-11-30 17:05:46 33 4
gpt4 key购买 nike

我写了两条鳕鱼。一个有效,而另一个则无效。请解释一下这段代码的工作原理以及为什么后者不起作用。

工作 -

    #include <stdio.h>
#include <malloc.h>

int main(){
int m, n, i, j;
scanf("%d%d",&m,&n);
int *p;
p = (int *) malloc(m*n*sizeof(int));
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%d", (p+i*n+j));
}
}
}

不工作 -

#include <stdio.h>
#include <malloc.h>

int main(){
int m, n, i, j;
scanf("%d%d",&m,&n);
int *p;
p = (int *) malloc(m*n*sizeof(int));
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%d", p[i][j]);
}
}
}

error is - subscripted value is neither array nor pointer nor vector
scanf("%d", p[i][j]);

最佳答案

对于第二个示例,p 需要是指向数组的指针,或指向指针的指针。

可能是这样的

int **p = malloc(m * sizeof(int *));
for (size_t i = 0; i < m; ++i)
{
p[i] = malloc(n * sizeof(int));
for (size_t j = 0; j < n; ++j)
{
scanf("%d", &p[i][j]);
}
}

关于创建一个以运行时尺寸作为输入的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35104419/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com