【发布时间】:2021-03-28 10:41:25
【问题描述】:
我现在正在学习 C,在尝试我的 uni 课程中的一些代码 sn-ps 时遇到了一个小问题。
这是关于指向结构的 typedef 指针及其在 sizeof() 函数中的用法。
#include <stdio.h>
#include <stdlib.h>
// Define struct
struct IntArrayStruct
{
int length;
int *array;
};
// Set typedef for pointer to struct
typedef struct IntArrayStruct *IntArrayRef;
// Declare function makeArray()
IntArrayRef makeArray(int length);
// Main function
int main(void)
{
// Use makeArray() to create a new array
int arraySize = 30;
IntArrayRef newArray = makeArray(arraySize);
}
// Define makeArray() with function body
IntArrayRef makeArray(int length)
{
IntArrayRef newArray = malloc(sizeof(*IntArrayRef)); // ERROR
newArray->length = length;
newArray->array = malloc(length * sizeof(int));
return newArray;
}
并且 代码在类 (Virtual C) 中使用的 IDE 中确实有效,但是当我在 VSCode 中尝试完全相同的示例并使用 GNU Make 或 GCC 编译它时,它返回一个错误因为malloc() 函数调用中的sizeof(*IntArrayRef) 被标记为意外的类型名称。
error: unexpected type name 'IntArrayRef': expected expression
但是,当我将其更改为 sizeof(IntArrayStruct) 时,一切正常。
*IntArrayRef 和 IntArrayStruct 的值不一样吗?
【问题讨论】:
-
使用
sizeof(*newArray)。 -
顺便说一句,通常认为 typedef 指针的风格很差。见stackoverflow.com/questions/750178/…
-
sizeof不是函数,而是运算符。代替sizeof(*newArray),使用sizeof *newArray -
sizeof(IntArrayStruct)在 C 中无效,因为IntArrayStruct是一个标签,而不是一个类型,并且没有意义,除非它前面有struct、union或enum,或者有是具有该名称的变量或 typedef。 (也许您将其编译为 C++?)。 -
@WilliamPursell 那么
sizeof *newArray * 4的结果是什么?是否与sizeof ( *newArray * 4 )或( sizeof *newArray ) * 4相同负责三年后代码维护的新聘开发人员知道吗?sizeof( *newArray )是明确。sizeof *newArray不是。
标签: c struct malloc pass-by-reference sizeof