0
数字を配列にスキャンする必要があるプログラムを作成しています。配列の項目数が5の倍数になることはわかっています。 realloc関数、mallocだけですが、私のプログラムは6番目の項目を混乱させ、10個の項目の後にクラッシュします。ここで私の誤りを見つけるのを助けてくれますか?ありがとう!malloc関数は配列項目を乱します(C)
#include <stdio.h>
#include <stdlib.h>
#define K 5
int main(){
int counter=0;
int enteredNum;
int *p=malloc(K*sizeof(int));
int *pmore=NULL;
printf("Please enter the series : \n");
scanf("%d",&enteredNum);
while(enteredNum!=0){
p[counter]=enteredNum;
if(counter%K==0&&counter!=0){
pmore=malloc(((counter)+K)*sizeof(int));
for(int i=0;i<counter;i++){
pmore[i]=p[i];
//for
free(p);
p=pmore;
pmore=NULL;
}//if
counter++;
scanf("%d",&enteredNum);
}
for(int i=0;i<counter;i++)
printf("%d\t",p[i]);
}
カウンタが6の場合は、最初に配列に書き込んだ後、要素に適合する新しいカウンタを作成します。あなたは "幸運なことに"あなたは6番目の要素。 ifの後と 'counter ++'の前に 'p [counter]'を動かしてください。 – apokryfos