게시판 즐겨찾기
편집
드래그 앤 드롭으로
즐겨찾기 아이콘 위치 수정이 가능합니다.
동적할당 예제 실행중 에러가 나는데..
게시물ID : programmer_12306짧은주소 복사하기
작성자 : ㅜ_ㅠ
추천 : 0
조회수 : 303회
댓글수 : 2개
등록시간 : 2015/07/24 12:10:36
아래의 예제를 실행하면 free(a);부분에서 자꾸 에러가 나네요.
그리고 a배열값도 전부 0밖에 나오지 않고
책에 있는 예제를 calloc함수가 void* 포인트를 리턴해서 int포인터 변수a에 대입할 수 없어서 int*로 형변환 해서 대입한 것을 제외하면 그대로 입력한건데 아무래도 뭔가 예제의 어느 부분이 잘못된거 같은데
아무리 봐도 예제의 어느부분이 잘못되있는지 모르겠네요,
아시는 분 답변 주셨으면 정말 좋겠네요.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void fill_array(int *a,int n);
int sum_array(int *a,int n);
void wrt_array(int *a,int n);

int main (void)

{
int *a,n;
srand (time(NULL));
printf("\n%s\n","This program does the following repeatedly:\n",
"\n"
"1 creates space for an array of size n \n"
"2 fills the array with randomly distributed digits\n"
"3 prints the array and the sum of its element\n");
for(;;){
printf("Input n: ");
if(scanf("%d",&n)!=1||n<1)
break;
putchar('\n');
a=(int *)calloc(n,sizeof(int));/*allocate space for a[]*/
fill_array(a,n);
wrt_array(a,n);
printf("Sum=%d\n\n",sum_array(a,n));
free(a);
}
printf("\nBye!\n\n");
return 0;
}
void fill_array(int *a,int n)
{
int i;
for(i=0;i<n;++i);
a[i]=rand()%19-9;
}
int sum_array(int *a,int n)
{
int i,sum=0;
for(i=0;i<n;++i)
sum+=a[i];
return sum;
}
void wrt_array(int *a,int n)
{
int i;
printf("a=[");
for(i=0;i<n;++i)
printf("%d%s",a[i],((i<n-1)?",":"]\n"));
}

전체 추천리스트 보기
새로운 댓글이 없습니다.
새로운 댓글 확인하기
글쓰기
◀뒤로가기
PC버전
맨위로▲
공지 운영 자료창고 청소년보호