【发布时间】:2015-02-17 06:25:07
【问题描述】:
我试图使用动态数组来计算积分的平均值,但是当我使用这些值运行时我的程序崩溃了:
- 2 1 1 1 1 3 1 1
如果我这样做,它不会崩溃:
- 2 1 1 1 1 4 1 1 1 1
如果我用 free() 删除 for 循环;里面
for (i=0 ; i<classes ; i++)
{ //free each individual 2unit array first
free(grades[i]); //This line doesnt work
}
它运行良好,但我不想这样做,因为我告诉过不要这样做。
这是代码,我尽量删除不必要的部分
#include<stdio.h>
#include<stdlib.h>
void fillArray(int **grades,int start,int finish)
{
int i;
for(i=start;i<finish;i++)
{
printf("Enter grade for Class %d: ",i+1);
scanf("%d",&grades[i][0]);
printf("Enter Credit for Class %d: ",i+1);
scanf("%d",&grades[i][1]);
}
}
void expandArray(int **grades,int oldSize,int newSize)
{
*grades = (int *)realloc(*grades,newSize*sizeof(int*)); //expanding the pointer array
int i;
for(i=oldSize;i<newSize;i++) //filling it with 2 unit arrays per class
{
grades[i] = (int *)malloc(2*sizeof(int));
}
fillArray(grades,oldSize,newSize);
}
int main()
{
int classes,oldClasses;
printf("Enter number of classes: ");
scanf("%d",&classes);
int **grades = (int **)malloc(classes*sizeof(int*)); //creating an array to store 2unit arrays(pointer array)
int i;
for(i=0;i<classes;i++) //filling the pointer array with 2 unit arrays per class
{
grades[i] = (int *)malloc(2*sizeof(int));
}
printf("Enter grades for each classes: \n");
fillArray(grades,0,classes); // this 0 here means we start at the index 0, that parameter is later used to start at the lastIndex+1
oldClasses = classes; // copied the value of classes to oldClasses instead of taking the new one as newClasses to avoid confusion.
printf("Enter new number of classes: ");
scanf("%d",&classes);
expandArray(grades,oldClasses,classes);
printf("This line works!");
for (i=0 ; i<classes ; i++)
{ //free each individual 2unit array first
free(grades[i]); //This line doesnt work
}
printf("This won't get printed with the value 3...");
free(grades); //free the pointer array (This one also works)
return 0;
}
【问题讨论】:
-
不要转换
malloc()的返回值。见stackoverflow.com/q/605845/3488231 -
我删除了所有 'malloc()' 上的演员表,我也尝试删除了 'realloc()' 上的演员表。但我仍然遇到崩溃
-
只是说这不是你应该做的事情。并不是说这是你崩溃的原因。否则我会把它作为答案发布,而不是评论。
-
哦,好吧,我投的原因是因为我被告知如果我不这样做,我的代码将与旧标准不兼容。不过感谢您提供的信息,如果将来遇到问题,我会尝试移除演员表
-
那给了你错误的提示,在 C 中
void*总是转换为任何数据指针类型。这会造成问题的唯一上下文是 C++,但无论如何,你不应该在那里使用malloc。
标签: c arrays dynamic crash realloc