简体   繁体   English

malloc 和结构体以及如何访问结构体的 malloc 内存

[英]malloc with structs and how to access memory of malloc of struct

if i have a simple struct such as How would i got about dynamically allocating memory for this struct using malloc?如果我有一个简单的结构,例如如何使用 malloc 为该结构动态分配内存?

struct Dimensions{
int height, width;
char name;
};

I um unsure on how to go about this, I have tried我不确定如何解决这个问题,我试过了

struct Dimension* dim = malloc(sizeof(struct Dimensions));

Also I would like then access the height and width variable in a loop later on in my code.此外,我希望稍后在我的代码中循环访问高度和宽度变量。 My first thought would be to use a pointer but im unsure on what this would exactly be.我的第一个想法是使用指针,但我不确定这到底是什么。

Would it be something like会不会像

int h = *width

I'm very new to C. Thanks我对 C 很陌生。谢谢

The way you dynamically allocated that struct is correct:您动态分配该结构的方式是正确的:

struct Dimension* dim = malloc(sizeof(struct Dimensions));

Also I would like then access the height and width variable in a loop later on in my code.此外,我希望稍后在我的代码中循环访问高度和宽度变量。

You should first assign some value to that dim first, something like:您应该首先为该dim分配一些值,例如:

dim->high = 1;
dim->width = 2;

The name member you just used a char which might not be what you need.您刚刚使用的name成员可能不是您需要的char Usually it's a string: char name[100];通常它是一个字符串: char name[100]; . . You can't use assignment for that string though, so use strcpy .但是,您不能对该字符串使用赋值,因此请使用strcpy

Then you can access that later:然后你可以稍后访问它:

int h = dim->high;

Remember once you're done with the dynamically allocated memory, you should free it:请记住,一旦您完成了动态分配的内存,您应该free它:

free(dim);
return 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM