为什么使用SomeType [1]而不是SomeType *作为结构中的最后一个成员 [英] Why use SomeType[1] instead of SomeType* as last member in structs

查看:189
本文介绍了为什么使用SomeType [1]而不是SomeType *作为结构中的最后一个成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码下面的语句中看到:

  SomeType someVar [1] 

后来 someVar SomeType 。为什么要这样声明它,而不是:

  SomeType * someVar; 

编辑:很多人指出,我需要指定上下文。

  struct SomeStruct 
{
size_t count;
SomeType someVar [1];
};

SomeStruct * str = malloc(sizeof(SomeStruct)+ sizeof(SomeType)* count);
str-> count = count
...

str-> someVar 用作 count 的元素的元素SomeType 从这一点开始。

解决方案

  SomeType someVar [1] 

someVar SomeType 有1个元素。

  SomeType * someVar; 

someVar / c>

$

b $ b

您可以使用数组的名称作为指向该数组第一个元素的指针的缩写。


Will Dean


I saw in the code next statement:

SomeType someVar[1];

Later someVar is used as a pointer to SomeType. Why would one declare it like this instead of:

SomeType* someVar;

EDIT: As many pointed out, I need to specify the context.

struct SomeStruct
{
    size_t count;
    SomeType someVar[1];
};

SomeStruct* str = malloc(sizeof(SomeStruct) + sizeof(SomeType) * count);
str->count = count
...

str->someVar is used as an array with count elements of SomeType from this point.

解决方案

SomeType someVar[1];

someVar is an array of type SomeType with 1 element.

SomeType* someVar;

someVar is a pointer (dangling still, you didn't point it to anything yet) of type SomeType.

And you can use the name of an array on its own as a shorthand for a pointer to the first element of that array.

Will Dean

这篇关于为什么使用SomeType [1]而不是SomeType *作为结构中的最后一个成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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