该程序的目标是扫描由数字和空格填充的字符串,并将每个数字插入数组。
这是我代码的相关部分-在尝试扫描和打印用户提供的字符串后,im遇到了奇怪的现象。
int main()
{
int exp,size,*numbers,sum=0;
char term,term2,*str=NULL,*n;
printf("Enter size of input:");
if(scanf("%d%c", &size, &term) != 2 || term != '\n'){//checking if a valid size was entered
printf("Invalid Size\n");
return 0;
} if(size<=0){//checking if a valid size was entered
printf("Invalid size\n");
return 0;
} else{//allocating memory to an array and a string with the supplied size
numbers=(int*)malloc(size * sizeof(int));
str=(char*)malloc(sizeof(int)*(size+1) + (size-1)*sizeof(char));
if(numbers==NULL||str==NULL){// in case memory allocation didn't work
printf("Out of memory\n");
return 0;
} else{
printf("Memory allocated\n");
}
printf("Enter numbers:");
scanf("%s",str);//trying to scan the string
printf("%s",*str);
free(numbers);
free(str);
}
}
当我完成为scanf行写输入并按Enter的那一刻,程序结束而没有打印,并且我得到警告:
warning : forat '%s' expects argument of type ' char *' , but argument 2 has type 'int' ..
所以我去了printf("%s",*str);
并将其更改为printf("%d",*str);
,但是正如您可能已经猜到的那样,它会吐出随机数。