gpt4 book ai didi

c - 动态分配char**

转载 作者:行者123 更新时间:2023-11-30 21:01:43 26 4
gpt4 key购买 nike

这是我的示例的文本:

Loading number N then N words from standard input. The word is not longer than 100 characters. Dynamically allocate array of loaded words as a series of pointers to character strings (dynamic array needs to have a type char **). Provide a set of words printed in a single line with spaces between the words.

有人可以告诉我如何设置字符限制吗?

我应该这样做吗:

scanf("%100s", str[i])

还是其他什么?
顺便说一句,我如何为这样的类型分配内存( char **int ** 等)?

这是我完成的代码,那么我做错了什么?

int main()
{
int i,n;
printf("How much words? "), scanf("%d", &n);
char *str= (char *)malloc(n*sizeof(char *));
for(i = 0; i < n; i++)
{
str[i] = malloc(100 * sizeof(char *));
printf("%d. word: ", i + 1),scanf("%s", str[i]);
}
for (i = 0; i < n; i++)
{
printf("%s ", str[i]);
}
getch();

最佳答案

指针数组类型错误

// char *str
char **str

带有注释的代码清理。

// add void
int main(void) {
int i,n;
// Easier to understand if on 2 lines-of code
printf("How much words? ");
// test scanf() results
if (scanf("%d", &n) != 1) return -1;

// Consider different style to allocate memory, as well as type change
// char *str= (char *)malloc(n*sizeof(char *));
char **str= malloc(sizeof *str * n);
// check allocation
assert(str == NULL);

for(i = 0; i < n; i++) {
str[i] = malloc(sizeof *str[i] * 100);
// check allocation
assert(str[i] == NULL);

printf("%d. word: ", i + 1);
fflush(stdout);

// limit input width to 99
// test scanf() results
if (scanf("%99s", str[i]) != 1) return -1;
}
for (i = 0; i < n; i++) {
// Add () to clearly show beginning/end of string
printf("(%s) ", str[i]);
}
getch();
}

关于c - 动态分配char**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34597426/

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