gpt4 book ai didi

c - 将标准输入存储到 C 语言的动态内存中

转载 作者:行者123 更新时间:2023-11-30 16:44:06 24 4
gpt4 key购买 nike

我现在正在使用 C 语言进行一些编码,只是为了提高我的 C 技能。我正在做的是将单词存储在分配的动态内存中,但在 **pointer 方面遇到一些困难...

例如,

while ((ch = getchar()) != EOF)

如果我输入 abcd efgh,则字符“abcd”应存储在 ptr[0][i] 中,第二个字符“efgh”应存储在存储在 ptr[1][i] 中,这应该通过循环完成。

我想通过初始化来完成,

char **ptr = (char**)malloc(sizeof(char*)*n);

这可能吗?

任何帮助将非常感激!

最佳答案

下面是在动态数组 (char **) 中存储一些字符串的示例。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
char **strings = NULL;
size_t nb_strings = 3;
size_t strings_length = 10;

strings = malloc( sizeof(*strings) * nb_strings );
// Now you can store 3 pointers to char

for (size_t index = 0 ; index < nb_strings ; index++)
strings[index] = malloc( sizeof(**strings) * strings_length );
// Every pointer points now to a memory area of 10 bytes

for (size_t index = 0 ; index < nb_strings ; index++)
{
strings[index][0] = '\0';
strncat( strings[index], "string", strings_length - 1 );
// You can store some strings now
}

for (size_t index = 0 ; index < nb_strings ; index++)
printf("strings[%zu] = %s.\n", index, strings[index]);
// You can check

for (size_t index = 0 ; index < nb_strings ; index++)
free(strings[index]);

free(strings);
// Do not forget to free

return (0);
}

关于c - 将标准输入存储到 C 语言的动态内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44726204/

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