简体   繁体   English

如何在AC结构中使用指向字符的指针?

[英]How to use a pointer to character within a c structure?

It is possible to declare a string of the required size using char name[size] , however if I want to use char *name , how will I specify the size that I require using malloc() ? 可以使用char name[size]声明所需大小的字符串,但是,如果我想使用char *name ,如何使用malloc()指定所需的大小?

I found out that I cannot use char *name = malloc(5*1); 我发现我不能使用char *name = malloc(5*1); within the structure declaration. 在结构声明中。

I have tried using 我尝试使用

struct data
{
    int age;
    char *name;
};

On running this code and entering the string I encountered Segmentation fault. 在运行此代码并输入字符串时,我遇到了细分错误。 How must I specify the size? 我该如何指定尺寸?

You need to specify the size of the pointer , you need to make the pointer to point to a valid memory, that's all. 您需要指定指针的大小 ,需要使指针指向有效的内存,仅此而已。 Moreover, it not necessary to use malloc() . 而且,没有必要使用malloc() You can either 你可以

  • allocate memory to the pointer via allocator functions, malloc() or family 通过分配器函数, malloc()或系列将内存分配给指针
  • make the pointer point to the address of any other char variable (or array) 使指针指向任何其他char变量(或数组)的地址

To elaborate, you create a variable var of type struct data , and then, make var->name point to a valid chunk of memory. 详细说来,您将创建一个struct data类型的变量var ,然后使var->name指向有效的内存块。

That said, to use malloc() for allocating required size of memory, you need to supply the required size as the argument to malloc() (in bytes). 也就是说,要使用malloc()分配所需的内存大小,您需要提供所需的大小作为malloc()的参数(以字节为单位)。

let's say you create a variable a of the type struct data 假设您创建了a struct data类型的变量a

struct data a;

Now allocate memory to the name member of a ie, 现在分配内存以名成员a

a.name = malloc(size_of_name + 1); //+1 for '\0' character at the end

Now you can use a.name to store and use the string 现在您可以使用a.name来存储和使用字符串

Don't forget to free the allocated data before terminating the program. 不要忘记在终止程序之前释放分配的数据。 for this use free(a.name) . 为此使用free(a.name)

You need to allocate the memory like: 您需要像这样分配内存:

data* r = malloc(sizeof(data));
r->name= malloc(20);

assuming the name can hold 20 chars 假设名称可以容纳20个字符

You'd need to supply a way to initialize your structure. 您需要提供一种初始化结构的方法。 For example: 例如:

void init_data (struct data *p_data) {
  if (p_data)
    p_data->name = malloc(STR_LEN);
}

And you should couple that with a function to free the memory: 您应该将其与释放内存的函数结合使用:

void release_data (struct data *p_data) {
  if (p_data)
    free(p_data->name);
}

It would than be called whenever you want to use your structure. 无论何时要使用结构,都将调用它。

struct data d;
init_data(&d);
/* use d */
release_data(&d);

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

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