【发布时间】:2016-12-07 15:44:33
【问题描述】:
我正在尝试编写一个小程序,它使用 realloc()、getchar() 和一些指针算法在内存中存储字符数组。
我有一个名为“inputArray”的函数(在 convert.c 中),它接收一个指向 char 的指针(以 NULL 开头,在 main.c 中声明),然后用一个 char 重新分配,直到 getchar() 得到一个 '\n' 字符。这些功能似乎工作正常,但是当我尝试在 main.c 中打印回字符串时,我收到“分段错误(核心转储)”错误。我一直在寻找几个小时,找不到问题所在。谢谢!
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';
}
转换.h:
#include <stdio.h>
#include <stdlib.h>
void inputArray(char * array);
【问题讨论】:
-
搜索并阅读有关在 c 中模拟通过引用传递。
-
sizeof(char)总是 1.....(好吧,如果你使用双角字符,可能是 2 - 但它是固定大小,这不是你想要的)。
标签: c arrays dynamic-allocation