I am quite new to C programming. 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).
I have read on this and it seems that I may be pointing to 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
分配内存。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.