Yash Kothari Yash Kothari - 6 days ago 5
C Question

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?

Answer

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

Comments