gpt4 book ai didi

c - 在 C 中标记用户输入(存储在 **arg 中)?

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

我正在尝试编写一个简单的类似 shell 的界面,它接受用户输入(通过字符)并通过指向指针 * 的指针存储它(argv 的工作原理)。这是我的代码:

char input[100];
char **argvInput;
char ch;
int charLoop = 0;
int wordCount = 0;

argvInput = malloc(25 * sizeof(char *));

while((ch = getc(stdin))) {
if ((ch == ' ' || ch == '\n') && charLoop != 0) {
input[charLoop] = '\0';
argvInput[wordCount] = malloc((charLoop + 1) * sizeof(char));
argvInput[wordCount] = input;
charLoop = 0;
wordCount++;

if (ch == '\n') {
break;
}

} else if (ch != ' ' && ch != '\n') {
input[charLoop] = ch;
charLoop++;
} else {
break;
}
}

如果我通过 argvInput 循环通过:

int i = 0;
for (i = 0; i < wordCount; i++)
printf("Word %i: %s\n", i, argvInput[i]);

argvInput[i] 的所有值都是最后一个输入分配的值。所以如果我输入:“快乐的日子快到了”,循环的输出是:

Word 0: soon
Word 1: soon
Word 2: soon
Word 3: soon
Word 4: soon

我很迷茫。显然每个循环都在覆盖以前的值,但我盯着屏幕,无法弄清楚为什么......

最佳答案

这一行是你的祸根:

    argvInput[wordCount] = input;

如果您要用另一个指针替换指向它的指针(即 input),那么分配新空间并不重要。

而是使用 strncpy 将部分 input 提取到 argvInput[wordCount] 中。

关于c - 在 C 中标记用户输入(存储在 **arg 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15015496/

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