正在尝试使用realloc(),正在转储内核
我正在尝试编写一个小程序,它使用realloc()、getchar()和一些指针算法在内存中存储字符数组 我有一个名为“inputArray”(在convert.c中)的函数,它接收一个指向字符的指针(开始为NULL,在main.c中声明),然后用一个字符重新分配,直到getchar()获得一个“\n”字符。这些函数似乎工作正常,但当我尝试将字符串打印回main.c时,我得到了一个“segmentation fault(core dumped)”错误。我已经找了好几个小时了,找不到问题出在哪里。谢谢 主要条款c:正在尝试使用realloc(),正在转储内核,c,arrays,dynamic-allocation,C,Arrays,Dynamic Allocation,我正在尝试编写一个小程序,它使用realloc()、getchar()和一些指针算法在内存中存储字符数组 我有一个名为“inputArray”(在convert.c中)的函数,它接收一个指向字符的指针(开始为NULL,在main.c中声明),然后用一个字符重新分配,直到getchar()获得一个“\n”字符。这些函数似乎工作正常,但当我尝试将字符串打印回main.c时,我得到了一个“segmentation fault(core dumped)”错误。我已经找了好几个小时了,找不到问题出在哪里。
# include "convert.h"
int main()
{
char * string = NULL;
inputArray(string);
printf("%s", string);
free(string);
return 0;
}
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);
#包括
#包括
无效输入阵列(字符*数组);
您在inputArray函数中缺少一级间接寻址。应该这样宣布
void inputArray(char **array)
char * inputArray(char * array);
void inputArray(char ** array);
它应该是这样的(您还需要将数组的大小乘以count+1
)
可以这样称呼:
inputArray(&string);
新分配阵列的大小不正确。您必须分配
count+1
个字符
array = realloc(array, ( count + 1 ) * sizeof(char));
考虑到使用临时指针重新分配内存更安全。否则,先前分配的内存的原始地址将丢失
还有这些声明
array = realloc(array, sizeof(char));
ptr += count;
你错了。你至少应该写信
array = realloc(array, count * sizeof(char));
ptr = array + count - 1;
函数也应该声明为
void inputArray(char **array)
char * inputArray(char * array);
void inputArray(char ** array);
它必须将新指针返回给调用者
主要是你必须写作
string = inputArray(string);
否则,函数应通过引用接受参数,该参数应声明为
void inputArray(char **array)
char * inputArray(char * array);
void inputArray(char ** array);
并在函数中进行相应的处理。搜索并阅读有关在c中模拟按引用传递的信息。
sizeof(char)
始终为1。。。。。(如果您使用的是双幅字符,可能是2个字符,但它是固定大小的,这不是您想要的)。@BeyelerStudios噢,匆忙的结果:-)@BeyelerStudios谢谢:-)