【问题标题】:How to allocate memory using struct and pointers [duplicate]如何使用结构和指针分配内存[重复]
【发布时间】:2021-10-04 13:26:21
【问题描述】:

我有一个名为 TCarro 的结构,具有此属性。

typedef struct {
  char nome[20];
  char placaDoCarro[5];
} TCarro;

我想知道如何动态分配这个变量struct TCarro *carro;。 比如当我使用scanf读取汽车数量时,我应该如何分配一些内存以便我可以做到carro[0]->...carro[1]->...,...

【问题讨论】:

  • 任何体面的初学者书籍、教程或课程都应该包含此信息。如果你没有书,或者不上课,那么我真的强烈建议你去买一些书,并可能报名参加一个课程。
  • TCarro *a = malloc(sizeof(TCarro)*nb_items); 类似的东西
  • 这能回答你的问题吗? malloc for struct and pointer in C
  • @Jean-FrançoisFabre 但如果我想查看有关 carro 的长度,使用 printf 出现此format specifies type 'int' but the argument has type 'struct TCarro *'
  • @VagnerWentz 您无法获取/显示动态分配数组的长度。您必须单独跟踪该值,即printf("%d", nb_items)

标签: c pointers struct


【解决方案1】:

要为结构动态分配内存,可以使用以下方法:

TCarro *carVariable=malloc(sizeof(TCarro)*someNumbers);

,其中someNumbers 是您要分配的元素数。

根据您在评论中发布的错误,我假设您尝试执行以下操作:

printf("%d",carVariable);

由于您在 printf (%d) 中指定了整数说明符,编译器希望该函数接收一个整数,但您改为给它一个 struct TCarro

所以现在您可能想知道,我可以使用什么说明符来打印我的carVariable

实际上,C 并没有提供这样的说明符,因为结构是程序员创建的类型,所以它不知道如何打印它。

如果你想打印你的变量,你可以做的是打印数组的每个单独的元素。

类似这样的:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct{
  char nome[20];
  char placaDoCarro[5];
}TCarro;

int main(void){
  size_t someNumbers=10; //if you want to allocate 10 cars
  TCarro *carVariable=malloc(sizeof(TCarro)*someNumbers);
  //notice that struct before TCarro is not needed, as you defined it as an existing type (named TCarro)

  strcpy(carVariable[0].nome,"Mercedes");
  strcpy(carVariable[0].placaDoCarro,"xxxx");

  strcpy(carVariable[1].nome,"Ford");
  strcpy(carVariable[1].placaDoCarro,"xxxx");
 
  //printf cars
  printf("%s %s\n",carVariable[0].nome, carVariable[0].placaDoCarro);
  printf("%s %s\n",carVariable[1].nome, carVariable[1].placaDoCarro);

  free(carVariable);
  return 0;
}

请注意,我使用了strcpy,因为我需要将一个字符串复制到结构的每个字段。

【讨论】:

  • 考虑调整到引用对象而不是类型:carVariable = malloc(sizeof(TCarro) * someNumbers); -->carVariable=malloc(sizeof( *carVariable * someNumbers);。更容易正确编码、审查和维护。
  • 您好,如果我想使用 scanf 读取汽车数量?
  • @chux-ReinstateMonica 我认为您的意思是“--> carVariable=malloc(sizeof(*carVariable) * someNumbers);”(您在sizeof 上缺少)
  • @VagnerWentz 然后你只需将scanf() 转换为someNumbers,然后再将someNumbers 传递给malloc()
  • 好的,现在我需要将作为参数创建的变量传递给functions.h中的另一个函数,我该怎么做?
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 2019-09-23
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
相关资源
最近更新 更多