gpt4 book ai didi

c - sizeof 报错值

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

我正在尝试使用 sizeof(_test.header.columns)/sizeof(struct _column) 从我自己的结构中获取“列”元素计数。不幸的是,我总是将其设置为 0,因为 sizeof(_test.header.columns) 始终为 4。这是代码:

struct _column{
char title[40];
int length;
};

struct test_struct{

struct{
struct _column* columns;
}header;

struct{
struct _column* columns;
}details;

struct{
struct _column* columns;
}end;
};

struct test_struct _test = {

.header = {
.columns = {
{
"a",
1,
},
{
"ab",
2,
},
},
},
.details = {
.columns = {
{
"b",
2,
},
{
"bc",
3,
},
},
},
.end = {
.columns = {
{
"c",
3,
},
{
"cd",
4,
},
},
},
};

void testme(){
char buff[20];
itoa(sizeof(_test.header.columns)/sizeof(struct _column),buff,sizeof(buff));
MessageBoxA(NULL,buff,NULL,NULL);
}

请帮我解决一下问题,谢谢。任何帮助将不胜感激。

最佳答案

您可能会尝试采用如下方法,其中执行相同类型的初始化,但将列计数本身包含为其中的一部分。

struct _column{
char title[40];
int length;
};

struct test_struct{

struct{
struct _column* columns;
int nColumns;
}header;

struct{
struct _column* columns;
int nColumns;
}details;

struct{
struct _column* columns;
int nColumns;
}end;
};

struct _column headerColumns [] = {
{
"a",
1
},
{
"ab",
2
}
};

struct _column detailColumns[] = {
{
"b",
2
},
{
"bc",
3
},
};

struct _column endColumns [] = {
{
"c",
3
},
{
"cd",
4
}
};

struct test_struct _test = {
{ headerColumns, sizeof(headerColumns)/sizeof(headerColumns[0])},
{ detailColumns, sizeof(detailColumns)/sizeof(detailColumns[0])},
{ endColumns, sizeof(endColumns)/sizeof(endColumns[0])}
};

关于c - sizeof 报错值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22382871/

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