gpt4 book ai didi

c - 将字符串添加到 C 中的结构

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

我是 C 的初学者,在使用 C 中的结构时遇到了一些麻烦。这是我的代码;

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

struct rec
{
char i;
char b;
char j;
} ;

int main()
{

struct rec *p;
p=(struct rec *) malloc (sizeof(struct rec));
(*p).i='hello';
(*p).b='world';
(*p).j ='there';
printf("%c %c %c\n",(*p).i,(*p).b,(*p).j);

free(p);
getch();
return 0;
}

这是; 欧德

我如何传递整个单词,而不是一个字母。

最佳答案

定义结构成员为char *:

struct rec
{
char *i;
char *b;
char *j;
} ;

并使用 printf%s:

printf("%s %s %s\n",(*p).i,(*p).b,(*p).j);

此外,您需要将 ' 替换为 ": (*p).j ="there"; 如果您分配字符串文字(可能无法修改),将结构成员更改为 const:

struct rec
{
const char *i;
const char *b;
const char *j;
} ;

关于c - 将字符串添加到 C 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9503283/

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