CaptainDaVinci
CaptainDaVinci

Reputation: 1065

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()?

I found out that I cannot use 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?

Upvotes: 2

Views: 77

Answers (4)

Cherubim
Cherubim

Reputation: 5457

let's say you create a variable a of the type struct data

struct data a;

Now allocate memory to the name member of a i.e,

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

Don't forget to free the allocated data before terminating the program. for this use free(a.name).

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

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(). You can either

  • allocate memory to the pointer via allocator functions, malloc() or family
  • make the pointer point to the address of any other char variable (or array)

To elaborate, you create a variable var of type struct data, and then, make var->name point to a valid chunk of memory.

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).

Upvotes: 3

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);

Upvotes: 1

You need to allocate the memory like:

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

assuming the name can hold 20 chars

Upvotes: 1

Related Questions