c - 在 C 中将 sizeof() 与指向结构的指针一起使用

标签 c struct malloc pass-by-reference sizeof

我现在正在学习 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) 时,一切都运行良好。

*IntArrayRefIntArrayStruct 的值不一样吗?

最佳答案

IntArrayRef 是类型的名称,因此 *IntArrayRef 是无效语法。您可以(并且应该)做的是给出变量的名称并取消引用:

IntArrayRef newArray = malloc(sizeof(*newArray)); 

关于c - 在 C 中将 sizeof() 与指向结构的指针一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65345819/

相关文章:

调用结构类型的函数并返回指针不运行

c - 如何在c中正确分配和打印结构指针?

c - Malloc for Structs 的问题

c - 不使用比较运算符的两个 double 据类型值的最大值

c - 使用指针返回修剪后的字符串

c - 从文本文件中读取整数并将它们排序到另一个文本文件和二进制文件中

go - 如何将 slice 元素传递给函数

c++ - 使用结构 C++ 进行转换

c - 使用 malloc 的段错误

c - 如何检查哪个进程正在运行?