结构体有什么特别之处? [英] What is special about structs?

查看:24
本文介绍了结构体有什么特别之处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在 C 语言中,我们不能从函数返回数组,而是返回指向数组的指针.但我想知道 structs 有什么特别之处,即使它们可能包含数组,它们也可以通过函数返回.

I know that in C we cannot return an array from a function, but a pointer to an array. But I want to know what is the special thing about structs that makes them return-able by functions even though they may contain arrays.

为什么 struct 包装使下面的程序有效?

Why is the struct wrapping makes the following program valid?

#include <stdio.h>

struct data {
    char buf[256];
};

struct data Foo(const char *buf);

int main(void)
{
    struct data obj;
    obj = Foo("This is a sentence.");
    printf("%s
", obj.buf);
    return 0;
}

struct data Foo(const char *buf)
{
    struct data X;
    strcpy(X.buf, buf);
    return X;
}

推荐答案

问同样问题的更好方法是数组有什么特别之处",因为它是附加了特殊处理的数组,而不是 <代码>结构s.

A better way of asking the same question would be "what is special about arrays", for it is the arrays that have special handling attached to them, not structs.

通过指针传递和返回数组的行为可以追溯到 C 的原始实现.数组衰减"为指针,引起了很多混乱,尤其是在刚接触该语言的人中.另一方面,结构体的行为就像内置类型,例如 ints、doubles 等.这包括嵌入在 struct 中的任何数组,除了 灵活数组成员,它们不是复制.

The behavior of passing and returning arrays by pointer traces back to the original implementation of C. Arrays "decay" to pointers, causing a good deal of confusion, especially among people new to the language. Structs, on the other hand, behave just like built-in types, such as ints, doubles, etc. This includes any arrays embedded in the struct, except for flexible array members, which are not copied.

这篇关于结构体有什么特别之处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆