我正在使用C语言编写一些代码来培养我的C技能。我正在做的是将文字存储在已分配的动态内存中,但在使用**指针时遇到一些困难......
例如,
while ((ch = getchar()) != EOF)
如果我输入abcd efgh
,则字符“abcd”应存储在ptr[0][i]
中,第二个字符“efgh”应存储在ptr[1][i]
中,这应该通过循环。
我想通过初始化来实现,
char **ptr = (char**)malloc(sizeof(char*)*n);
这可能吗?
任何帮助都会非常感谢!
答案 0 :(得分:0)
以下是在动态数组中存储一些字符串的示例(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);
}
答案 1 :(得分:0)
您需要了解realloc()。你有两个级别的列表,你有一个单词列表,当输入新单词时必须扩展,每个单词都是一个字符列表。
从一个空的单词列表开始
char **words = 0;
int Nwords = 0;
一个空字
char *word = 0;
int wordlen = 0;
正如您所做的那样,我们的主循环是输入
的字符读取 while( (ch = getchar()) != EOF)
{
/* logic here */
}
那么逻辑是什么?
while( (ch = getchar()) != EOF)
{
if(!isspace(ch))
{
/* add letter to word */
}
else
{
if(wordlen > 0)
{
/* add word to word list */
}
}
}
我可以填写评论,但那会为你做。您使用realloc()为每个新条目增加缓冲区。