我现在正在学习 C,在尝试我的大学类(class)中的一些代码片段时遇到了一个小问题。
这是关于指向结构的 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
的值不一样吗?
最佳答案
IntArrayRef
是类型的名称,因此 *IntArrayRef
是无效语法。您可以(并且应该)做的是给出变量的名称并取消引用:
IntArrayRef newArray = malloc(sizeof(*newArray));
关于c - 在 C 中将 sizeof() 与指向结构的指针一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65345819/