my program is crash

why my programm is die
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<stdio.h>
#include<stdlib.h>
typedef struct{
	int *data;
	int size;
}array;
void array_inital(array *a){
	a->size=0;
	a->data=NULL;
}
void array_resize(array *a,int new_size){
	int i;
	int *new_data=(int*)malloc(sizeof(int)*new_size);
	if(!new_data){
		printf("cannot allocate");
	}
	for(i=0;i<new_size;i++){
		new_data[i]=a->data[i];
	}
	a->data=new_data;
	a->size=new_size;
	
}
void array_append(array *a,int i){
	array_resize(a,a->size+1);
	a->data[a->size-1]=i;
}
void array_input(array *a){

while(1){
int i;	
printf("Input the number ");
scanf("%d",&i);
if(i<0){
	break;
}	
array_append(a,i);
}

}
void array_output(array *a){
	int i;
	for(i=0;i<a->size;i++){
		printf("%d \n",a->data[i]);
	}
}
int main(){
	array a;
	int i;
	array_inital(&a);
	array_input(&a);
	array_output(&a);
}
Last edited on
1. How many elements are in the a->data in lines 17-19?

2. What happens on line 20to the memory that the a->data points to before line 20?
Line 17, change new_size to a->size. You need to copy the old number of elements, not the new one. In particular, when the array is new, the size is zero and you need to copy NO elements.

Remove line 49. i is unused.

Although your code will work with these changes, it's inefficient because it resizes the array every time you add a new element. A more efficient way to do this is to allocate space for extra elements each time. Then you have to keep track of both now many elements are used (the size) and how much room is available for new elements (the capacity).

Adding this stuff might be beyond the purpose of your assignment though.

Also, your code C, not C++. If you're meant to do this in C++ then it would be better to do it as a class.
thx bro!!
Topic archived. No new replies allowed.