【问题标题】:Why this code gives runtime error?为什么这段代码会给出运行时错误?
【发布时间】:2015-03-21 12:18:38
【问题描述】:

将二维数组传递给函数。 为什么这段代码会出现运行时错误?

#include<stdio.h>
void cpc(int **x){
int i,j;
for(i=0;i<3;printf("\n"),i++)
  for(j=0;j<3;j++)
    {
    printf("%d ",(*(*(x+i)+j)));
    }
}
int main(){
int a[3][3] = {1,2,3,4,5,6,7,8,9};
int **b = (int**)a ;
cpc(b);
return 0;
}

【问题讨论】:

  • 什么是 printf("\n") 以及第一个循环的左括号在哪里
  • @Abhi 不会造成任何问题..肯定

标签: arrays function pointers arguments


【解决方案1】:

您代码中的问题是 a[3][3] 不是 int **,它是 int * 并且是连续内存。

这是您的代码可以工作的方式之一。

#include<stdio.h>
void cpc(int **x){
int i,j;
for(i=0;i<3;printf("\n"),i++)
  for(j=0;j<3;j++)
    {
    printf("%d ",(*(*x+(3*i)+j)));
    }
}
int main(){
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int *b = a;
cpc(&b);
return 0;
}

如果您想在 cpc 函数中使用 int **,您应该在矩阵中动态分配行内存。在这里你可以找到一个例子。

#include<stdio.h>
#include<stdlib.h>
void cpc(int **x){
int i,j;
for(i=0;i<3;printf("\n"),i++)
  for(j=0;j<3;j++)
    {
    printf("%d ",(*(*(x+i)+j)));
    }
}
int main(){
int *a[3];
for (int i=0;i<3;i++)
{
  a[i] = malloc(sizeof(int)*3);
  for (int j=0;j<3;j++)
    a[i][j] = i*3+j;
}
int **b = a;
cpc(b);
return 0;
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多