gpt4 book ai didi

c - 来自用户输入的动态指针数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:48 24 4
gpt4 key购买 nike

关于 C 中指针数组的动态分配,我需要一些帮助。我正在尝试创建一个程序,从用户输入中读取单词的句子,并将单词存储在字符数组字符串中。然后我想将指向这些单词的指针 char *word 保存在指针数组 char **wordArray 中。

为单词创建一个动态分配的工作方法非常简单,它从用户输入中逐个字符地读取。但是,尝试将此方法应用于指针数组比较棘手。

当前函数 char **varArray 显然有缺陷,但我的想法是“当用户输入时,获取指针数组的单词指针”。它现在有效地循环每个 char c 的第一个单词。

我的问题是,如何实现指针数组的第二层 (char **varArray()) 动态内存分配?该函数如何检测何时调用 char *word()

对于代码、样式或其他错误的反馈当然会受到欢迎。我的水平是中级初学者。

/*CREATES AND ALLOCATES DYNAMIC VARIABLE ARRAY*/
#include <stdio.h>
#include <stdlib.h>

char **varArray();
char *word();

char **varArray()
{
char **tmp=NULL;
char **wordArray=NULL;
size_t size=0;
char c = EOF;
int words=0;

while(c) {
c=getc(stdin);
if (c == EOF || c == '\n')
c=0;

if (size <= words) {
size+=sizeof(char *);
tmp = realloc(wordArray,size);

if(tmp == NULL) {
free(wordArray);
wordArray=NULL;
printf("Memory allocation failed. Aborted.\n");
break;
}

wordArray=tmp;
}
words++;
wordArray[words]= word();
return wordArray;
}

检索ONE word的方法:

/*GETS ONE WORD FROM USER INPUT*/
char *word()
{
char *word=NULL, *tmp=NULL;
size_t size=0;
char c = EOF;
int letters=0;

while(c) { //reads character by character
c=getc(stdin);

if (c == EOF || c == '\n' || c==' ') //remove ' ' to read all input
c =0;

if (size <= letters) { //increase and reallocate memory
size = size + sizeof(char);
tmp = realloc(word,size);

if (tmp==NULL) { //check if allocation failed
free(word);
word=NULL;
printf("Memory allocation failed. Aborted.\n");
break;
}
word= tmp;
}
letters=letters+1;
word[letters]=c;

}
/*ADD SENTINEL CHARACTER*/
letters++;
size += sizeof(char);
word = realloc(word,size);
word[letters]='\n';
return word;
}

最佳答案

这是您要编写的程序的框架。

 ...
char* currentWord;
char **wordArray=NULL;
while ((currentWord = word()) != NULL) {
.... add current word to word array with realloc...
}
....

char* word() {
int ch;
char* outputWord = NULL;
while ((ch = getch()) != EOF) {
if ( ... ch is a word character ... )
... add ch to output word with realloc ...
else {
char* ret = outputWord;
outputWord = NULL;
return ret;
}
}
return NULL;
}

请注意两个 while 循环是如何做完全相同的事情的。

  while ((element = getNextElement()) != sentinelValue) {  
.... process newly obtained element ....
}

关于c - 来自用户输入的动态指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46624370/

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