gpt4 book ai didi

c - c中逐个字符的结构成员

转载 作者:行者123 更新时间:2023-12-04 06:41:26 25 4
gpt4 key购买 nike

如何逐个字符地为结构成员赋值。我想做类似的事情

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

struct s
{
char *z;
};

int main ()
{

struct s *ss;
ss = malloc(2 * sizeof *ss);

char *str = "Hello World-Bye Foo Bar";
char *a = str;
int i = 0;
while (*a != '\0') {
if (*a == '-')
i++;
else ss[i].z = *a; // can I do this?
a++;
}
for(i = 0; i<2; i++)
printf("%s\n",ss[i].z);
}

所以我可以得到一些东西:
ss[0].z = "Hello World"
ss[1].z = "-Bye Foo Bar"

编辑:忘了说了, str中“-”的个数可能会有所不同。

最佳答案

const char *str不是 const 你可以插入 '\0'将字符串分成两部分。这样做时,您还需要将其他字符移到“正确”。

更清洁的解决方案是使用类似 strdup 的东西。制作字符串的两个副本,其中一个您提前终止,另一个您在中途开始复制:

例如

ss[0].z = strdup(str);
ss[1].z = strdup(strchr(str, '-'));
const size_t fist_part = strlen(str)-strlen(ss[1].z);
ss[0].z[first_part] = 0;

更新:您可以使用它,即使有多个“-”
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct s
{
char *z;
};

int main ()
{
struct s *ss;
ss = malloc(20 * sizeof(struct s));

const char *str = "Hello World-Bye Foo Bar-more-and-more-things";
int i = 1;
char *found = NULL;
ss[0].z = strdup(str);
while ((found = strchr(ss[i-1].z, '-'))) {
// TODO: check found+1 is valid!
ss[i].z = strdup(found+1);
*found = 0;
++i;
}
for(i = 0; i<6; i++)
printf("%s\n",ss[i].z);

return EXIT_SUCCESS;
}

在实践中,您希望更加小心地避免出现意外输入的错误,因此您需要确保处理:
  • 没有“-”字符
  • 没有 '\0' 字符
  • 分配失败

  • 别忘了 free()也!

    关于c - c中逐个字符的结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4190042/

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