gpt4 book ai didi

c - 如何在 C 中创建(和使用)指向字符串数组的指针数组?

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

我需要创建一个指针数组,每个指针都指向一个字符串数组。基础是一个大小为 2 的字符串数组(字符串的长度在开始时是未知的)。例如 2 个字符串的数组(名字和姓氏):

char *name[2];

现在我需要创建一个未知大小(由用户输入)的数组,它将指向我刚刚创建的类型。我的想法是以这种方式创建它:

char **people=name;

然后询问用户他想输入多少个名字,并分配足够的空间来容纳所有的名字。

people=(char**)malloc(sizeof(char*)*num); //num is the number received by the user.

这就是事情对我来说变得太复杂的地方,我无法弄清楚如何调用每个单独的名称以在其中放入一个字符串。我构建了一个将接收所有名称的循环,但我不知道如何正确存储它们。

for(i=0;i<num;i++){
printf("Please enter the #%d first and last name:\n",i+1);
//Receives the first name.
scanf("%s",&bufferFirstName);
getchar();
//Receives the last name (can also include spaces).
gets(bufferLastName);
people[i][0]=(char*)malloc(strlen(bufferFirstName)+1);
people[i][1]=(char*)malloc(strlen(bufferLastName)+1);
//^^Needless to say that it won't even compile :(
}

谁能告诉我如何正确使用这种点数组?谢谢。

最佳答案

来自 cdecl :

declare foo as array of pointer to array 2 of pointer to char

char *(*foo[])[2];

因此,foo[0] 是指向 char * 数组 2 的指针

那是数组,但为了您的使用,您需要:

declare foo as pointer to array 2 of pointer to char;

char *(*foo)[2];

现在您可以:

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

int main() {
char *(*foo)[2];

printf("How many people?\n");
int n; scanf("%d", &n);

foo = malloc(sizeof *foo * n);

for (int i = 0; i < n; i++) {
char bufFirstName[1024];
char bufLastName[1024];

printf("Please insert the #%d first and last name:\n", i+1);

scanf("%s %s", bufFirstName, bufLastName);

char *firstName = malloc(strlen(bufFirstName) + 1);
char *lastName = malloc(strlen(bufLastName) + 1);

strcpy(firstName, bufFirstName);
strcpy(lastName, bufLastName);

foo[i][0] = firstName;
foo[i][1] = lastName;
}

for (int i = 0; i < n; i++) {
printf("Name: %s LastName: %s\n", foo[i][0], foo[i][1]);
}

return 0;
}

-std=c99编译

请注意,像这样使用 scanfstrcpystrlen 是不安全的,因为可能会发生缓冲区溢出。

另外,记得释放你的 malloc!

关于c - 如何在 C 中创建(和使用)指向字符串数组的指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20529139/

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