有什么特殊的结构? [英] What is special about structs?

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

问题描述

我知道,在C,我们不能从一个函数返回一个数组,而是一个指针数组。但我想知道什么是关于结构的特别的东西,使他们回归,能够通过功能,即使它们可能包含数组。

为什么结构换行,下面的程序合法吗?

 的#include<&stdio.h中GT;结构数据{
    焦炭BUF [256];
};结构数据美孚(为const char * BUF);INT主要(无效)
{
    结构数据OBJ;
    OBJ =美孚(这是一个句子。);
    的printf(%S \\ n,obj.buf);
    返回0;
}结构数据美孚(为const char * BUF)
{
    结构数据X;
    的strcpy(X.buf,BUF);
    返回X;
}


解决方案

问同样的问题将是有什么特别之处阵列,因为它是有附加到他们,而不是特殊处理的阵列的一个更好的办法结构秒。

传递和返回数组的指针类型的行为可以追溯到原始的实现C.阵列衰变的指针,造成混乱的一个很好的协议,尤其是人民的新的语言。结构,另一方面,表现就像内置类型,如 INT S,双击 S,等这包括嵌入在结构,除了灵活的阵列中的任何阵列成员,这是不可复制的。

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.

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\n", obj.buf);
    return 0;
}

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

解决方案

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.

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天全站免登陆