【发布时间】:2014-04-24 21:21:10
【问题描述】:
我是 C 编程和学习指针以及使用指针实现二维数组的新手和新手。我在执行以下程序时遇到运行时错误,该程序编译时没有任何投诉,但在运行时崩溃并显示消息“分段错误(核心转储)”。如果我在不使用 malloc(用于动态内存分配)的情况下运行程序,它会完美运行。我在 Ubuntu linux 上使用 gcc 编译器。
#include<stdio.h>
#include<stdlib.h>
#define ROW 3
#define COL 3
main()
{
int *arr[ROW];
int i,j;
arr[ROW] = (int *) malloc(COL * sizeof(int)); //dynamic memory allocation
printf("\nEnter values\n\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
scanf("%d",(*(arr+i)+j));
}
printf("\nEntered values are\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
printf("\t%d",*(*(arr+i)+j));
printf("\n");
}
printf("\n");
}
程序在运行时崩溃并显示以下消息:
Segmentation fault (core dumped)
以下版本的程序(不带malloc)完美执行,没有任何错误
#include<stdio.h>
#include<stdlib.h>
#define ROW 3
#define COL 3
main()
{
int *arr[ROW][COL];
int i,j;
printf("\nEnter values\n\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
scanf("%d",(*(arr+i)+j));
}
printf("\nEntered values are\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
printf("\t%d",*(*(arr+i)+j));
printf("\n");
}
printf("\n");
}
【问题讨论】:
-
如果代码缩进良好,那就太好了。
标签: c arrays pointers segmentation-fault malloc