结构体有什么特别之处?

编程入门 行业动态 更新时间:2024-10-23 15:29:17
本文介绍了结构体有什么特别之处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道在 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.

更多推荐

结构体有什么特别之处?

本文发布于:2023-07-27 02:59:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219948.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么   之处   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!