私はrealloc()、getchar()とポインタの算術演算を使ってメモリに文字の配列を格納する小さなプログラムを書こうとしています。realloc()、コアのダンプを取得しようとしました
私はcharへのポインタ(main.cで宣言されている、最初はNULLです)を受け取る "inputArray"と呼ばれる関数を持っていて、getchar()が呼び出されるまで1つのcharで再割り当てされます。 '\ n'文字を取得します。関数は正常に動作するようだが、main.cに文字列を戻そうとすると、 "segmentation fault(core dumped)"というエラーが出る。私は何時間も探していて、どこに問題があるのか分からない。ありがとう!
のmain.c:
# include "convert.h"
int main()
{
char * string = NULL;
inputArray(string);
printf("%s", string);
free(string);
return 0;
}
convert.c:
#include "convert.h"
void inputArray(char * array)
{
/*pointer to the array*/
char * ptr = NULL;
/*stores the char*/
char c = 0;
/*counter used for pointer arithmetic*/
int count = 0;
/*loop for getting chars in array*/
while ((c = getchar()) != '\n')
{
array = realloc(array, sizeof(char));
ptr = array + count;
*ptr = c;
++count;
}
/*add the null char to the end of the string*/
array = realloc(array, sizeof(char));
ptr += count;
*ptr = '\0';
}
CONVERT.H:
#include <stdio.h>
#include <stdlib.h>
void inputArray(char * array);
*をc *で参照してエミュレートすることについて検索して読んでください。 –
'sizeof(char)'は常に1 .....になります(ダブル幅の文字を使用している場合は2つですが、固定サイズです)。 – gilez