c 中结构体的大小 - size_t
由于某种原因,当我尝试获取结构的大小时,我不断遇到分段错误。
struct my_struct {
char *a;
int b;
};
int main(int argc, char *argv[])
{
struct my_struct dastruct;
size_t len = sizeof(dastruct) / sizeof(struct my_struct); // error
qsort(dastruct, len, sizeof(struct my_struct), cmp);
...
}
有什么想法我做错了吗?谢谢
For some reason I keep getting segmentation fault when I try to get the size of my struct.
struct my_struct {
char *a;
int b;
};
int main(int argc, char *argv[])
{
struct my_struct dastruct;
size_t len = sizeof(dastruct) / sizeof(struct my_struct); // error
qsort(dastruct, len, sizeof(struct my_struct), cmp);
...
}
Any ideas what I'm doing wrong? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您在该行发生崩溃
,则可能是由于
sizeof(struct my_struct)
计算结果为 0 引起的。(即问题实际上是除以零)。当类型struct my_struct
不完整(即未定义)时,某些编译器可能会发生这种情况。在sizeof
中使用不完整类型在 C 中是非法的,但某些编译器出于某种原因允许这样做,并将其计算为 0。(尽管我希望编译器在编译时捕获此除以 0 的情况。)你的代码显然是假的,并不能说明问题。如果上述理论是正确的,那么很可能在您的实际代码中,您在
sizeof
中输错了类型struct my_struct
的名称,或者忘记包含类型的定义>结构my_struct
。(可能性很小,但无论如何......)
If you are getting the crash specifically at the
line, it might be caused by
sizeof(struct my_struct)
evaluating to 0. (I.e the problem is actually the division by zero). This might happen in some compilers when typestruct my_struct
is incomplete, i.e. it is not defined. Using incomplete type insizeof
is illegal in C, but some compilers allow it for some reason, evaluating it to 0. (Although I'd expect the compiler to catch this division by 0 at compile time.)Your code is obviously fake and doesn't illustrate the problem. If the above theory is correct, most likely in your real code you either mistyped the name of the type
struct my_struct
insizeof
or forgot to include the definition of the typestruct my_struct
.(Highly unlikely, but anyway...)
您可能想让
dastruct
成为一个数组。编辑:您也没有给出
cmp
,因此不可能说那里是否有问题(我认为这将是发生分段错误的地方)。You probably want to make
dastruct
an array.Edit: You've also not given
cmp
, so its not possible to say if something is wrong there (which I see would be the place the segmentation fault occurs).我唯一能看到的是你忘记了
#include
。请记住,C 在第一次使用时隐式声明了qsort
。The only thing I can possibly see is that you forgot to
#include <stdlib.h>
. Remember that C implicitly declares aqsort
at the first use.如果您发布的代码是完整的代码,那么您未能初始化 dastruct 的 a 指针成员,因此它指向某个无效位置。当
qsort()
调用可能使用该指针的cmp()
时(您尚未显示该代码),您可能会遇到段错误。请注意,我假设您的段错误发生在除仅除两个常量的 len 初始化之外的某个地方(无论如何,这很可能在编译时发生)。
If your code as posted is your complete code, then you have failed to initialise the
a
pointer member ofdastruct
, so it's pointing off into some invalid location. Whenqsort()
callscmp()
which presumably uses that pointer (you haven't shown that code), you are likely to get a segfault.Note that I'm assuming your segfault happens at some place other than the initialisation of
len
that only divides two constants (which is likely to happen at compile time anyway).