gpt4 book ai didi

c++ - 在嵌套结构中分配 const char* (c++)

转载 作者:行者123 更新时间:2023-11-28 06:47:40 25 4
gpt4 key购买 nike

我正在尝试在嵌套结构中分配一个 const char* 值。我想将名字和名字分配给一个字符值,而不是一个字符串。这是我知道的更多 c,但我使用的是 C++。这是我的问题:

struct person {
const char* name;
const char* firstname;
};


struct person_struct {
int pers_num;
struct person* data;
};

// How does the assignment work?... i know this is wrong:
char name[100] = "Jason";
char firstname[100] = "Conner";
struct person_struct pers_info;
pers_info.pers_num = 1;
pers_info->data->name = new char[strlen(name)+1];
pers_info->data->firstname = new char[strlen(firstname)+1]

非常感谢大家的帮助!!! :-)

[编辑:]

错误:

error: expected constructor, destructor, or type conversion before â.â token
error: expected constructor, destructor, or type conversion before â->â token
error: expected constructor, destructor, or type conversion before â->â token

最佳答案

strdup()将是一种方法(将其保留在纯 C 中)

当然首先你需要分配足够数量的person结构体

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

typedef struct person_ {
const char* name;
const char* firstname;
} person;

struct person_struct {
int pers_num;
person* data;
} PS;



int main(void) {
char name[100] = "Jason";
char firstname[100] = "Conner";

PS.pers_num=1;
// added cast here
PS.data = (person*)calloc(PS.pers_num, sizeof(person));
PS.data[0].name = strdup(name);
PS.data[0].firstname = strdup(firstname);

puts(PS.data[0].name);
puts(PS.data[0].firstname);

return 0;
}

关于c++ - 在嵌套结构中分配 const char* (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24672892/

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