【发布时间】:2020-07-17 14:49:00
【问题描述】:
我是编码新手,也是 C++ 新手。我正在尝试编写一个输入矩阵元素的代码。之后,应删除一列,并添加一行。删除一列工作正常。但是,在为新的行数重新分配内存后,我收到消息:分段错误(核心转储)。我正在使用指针来创建和编辑我的矩阵。这是我的代码。感谢您的帮助!
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c,r,**p,column,row;
printf("Enter the number of rows and columns:\n");
scanf("%d\n%d",&r,&c);
p=(int**)calloc(r,sizeof(int*));
if(p==NULL) printf("Memory not allocated.\n");
else{
for(int i=0;i<r;i++){
*(p+i)=(int*)calloc(c,sizeof(int));
printf("Enter %d. row\n",i+1);
for(int j=0;j<c;j++){
scanf("%d",*(p+i)+j);
}
}
printf("Original matrix:\n");
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
printf("%d ",*(*(p+i)+j));
}
printf("\n");
}
printf("Which column do you want to remove?");
scanf("%d",&column);
while(column<1||column>c){
printf("Wrong entry, enter again:");
scanf("%d",&column);
}
for(int i=0;i<=r-1;i++){
for(int j=column-1;j<=c-2;j++)
*(*(p+i)+j)=*(*(p+i)+j+1);
*(p+i)=(int*)realloc(*(p+i),(c-1)*sizeof(int));
}
printf("Matrix without %d. column:\n",column);
for(int i=0;i<r;i++){
for(int j=0;j<c-1;j++)
printf("%d ",*(*(p+i)+j));
printf("\n");
}
printf("Which row do you want to replace?\n");
scanf("%d",&row);
while(row<1||row>r){
printf("Wrong entry, enter again:\n");
scanf("%d",&row);
}
p=(int**)realloc(p,(r+1)*sizeof(int*));
if(p==NULL)
printf("Memory not allocated.\n");
else{
printf("Enter %d. row",row);
for(int i=r+1;i>row-1;i++){
*(p+i)=*(p+i-1);
}
for(int j=0;j<c-2;j++)
scanf("%d",*(p+row-1)+j);
printf("New matrix:\n");
for(int i=0;i<=r;i++){
for(int j=0;j<c-2;j++)
printf("%d ",*(*(p+i)+j));
printf("\n");
}
}
}
return 0;
}
【问题讨论】:
-
使用
std::vector或std::array。手动动态内存真的不适合初学者。经过多年的 C++,我仍然没有为它做好准备;) -
嗯,第一个问题就是上面的代码不是C++,而是C代码。如果你真的想学习C++,你需要start with a good C++ book。
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用debugger 来单步执行您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.
-
不要在现代 C++ 中进行手动内存管理。 特别是如果您是新手。使用容器和智能指针。 不是
new/delete和 当然不是malloc/calloc/realloc/free在 C++ 中 - 从你的记忆中删除那些,忘记它们的存在 - C++ 不是 C.
标签: c matrix segmentation-fault memory-reallocation