[英]C Programming EXC_BAD_ACCESS on very basic C program
I am quite new to C programming. 我是C编程的新手。 I need to write a programm that works with dynamic Arrays. 我需要编写一个与动态数组配合使用的程序。 (Takes in Values and doubles the size of the Array, when it is full). (当数据已满时,取值并使数组的大小加倍)。 My programm is finished and compilation works but I keep on getting this Error in the commented line: Thread 1: EXC_BAD_ACCESS (code=2, address:(some long adress). 我的程序已完成并且编译工作但我继续在注释行中得到此错误:线程1:EXC_BAD_ACCESS(代码= 2,地址:(一些长地址)。
I have read on this and it seems that I may be pointing to null. 我已经读过这个,似乎我可能指向null。 But a null test didn't do the job. 但是空测试没有完成这项工作。 I'Ve had this problem in other programms before and I seem to be missing a basic point. 我之前在其他程序中遇到过这个问题,我似乎错过了一个基本点。 Can somebody help me with this please! 请有人帮我这个! This is my code: 这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int *value;
int size;
int MAX;
} DynArray;
void dyn_array_add (DynArray* array){
int wert;
int *temp;
printf("Geben Sie einen Wert ein:\n");
scanf("%i", &wert);
if (array->MAX==array->size) {
for (int i= 0; i<array->MAX; i++) {
temp[i] = array->value[i]; // error occurs HERE
}
free(array->value);
array->MAX = array->MAX*2;
array->value=malloc(sizeof(int)* array->MAX);
for (int i= 0; i<array->MAX; i++) {
array->value[i] = temp[i];
}
}
array->value[array->size]= wert;
array->size++;
for (int i = 0; i < array->MAX; i++) {
printf("Value[%i]: %i \n", i, array->value[i]);
}
}
int main(int argc, const char * argv[]) {
DynArray* array;
array = (DynArray*)malloc(sizeof(DynArray));
array->MAX=5;
array->size=0;
array->value=malloc(sizeof(int)* array->MAX);
while (1) {
dyn_array_add(array);
}
return 0;
}
temp[i] = array->value[i]; // error occurs HERE
显然,因为你没有为temp
分配内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.