gpt4 book ai didi

c - 动态数组 malloc 清空单独的数组

转载 作者:行者123 更新时间:2023-12-04 18:12:05 24 4
gpt4 key购买 nike

我遇到了动态数组和 malloc 的问题.我对C相当陌生,所以请原谅(并建议)任何新手错误。

问题是我创建了一个数组(在本例中为 input_string)并将其传递给 func2 .然后在 func2我做一个测试,打印出 input_string 的第一个元素。

这在 malloc 之前的第一个打印输出中按预期工作。 , 但在 malloc 之后它不打印任何东西。这对我来说似乎很奇怪,因为在 printf 之间语句我对 input_string 什么都不做。

我假设我处理这些数组不正确,但我不确定。

这是有问题的代码片段:

更新

... // includes not in snippet

/* CONSTANTS */
#define LINE_LEN 80

/* Function declarations */
char* func1(void);
char* func2(int tl, char* input_string);

int main(void) {
char* input_string;
int tab_length;
char* output_string;

input_string = func1();
output_string = func2(tl, input_string);

return 0;
}

char* func1(void) {
char cur_char;
char* input_ptr;
char input_string[LINE_LEN];
while ((cur_char = getchar()) != '\n' && chars_read < 80) {
// iterate and create the array here
}
input_ptr = &input_string[0]; /* set pointer to address of 0th index */
return input_ptr;
}

char* func2(int tl, char* input_string) {
int n = 0, output_idx = 0;
char* output_ptr;
printf("\nBefore malloc: %c ", *(input_string));
output_ptr = malloc(tab_length * chars_read+1);
if (output_ptr == NULL) {
printf("Failed to allocate memory for output_ptr.\nExiting");
exit(1);
}
printf("\nAfter malloc: %c ", *(input_string));
...
return output_ptr;
}

P.s.:任何未声明的变量都已在此代码段之外声明。

更新

感谢所有的回复和建议。这是非常赞赏。

最佳答案

func1返回一个指向临时字符串的指针。你没有分配它。这将产生未定义的行为。

相反,您应该这样做:

char* func1(void) {
char cur_char;
char* input_ptr = (char*)malloc(LINE_LEN * sizeof(char));
while ((cur_char = getchar()) != '\n' && chars_read < 80) {
// iterate and create the array here
}
return input_ptr;
}

有趣的是,您确实使用了 malloc里面 func2 .

完成后需要调用 free释放内存。
int main(void) {
char* input_string;
int tab_length;
char* output_string;

input_string = func1();
output_string = func2(tl, input_string);

free(input_string);
free(output_string);

return 0;
}

关于c - 动态数组 malloc 清空单独的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12417631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com