-1

I'm using this structure below, but it's limited if I want to get all String from a huge file...

typedef struct arr {
    char name[200]; // Could be a number higher than 200 here...
} array;

Now, if I use...

typedef struct arr {
    char *name;
} array;

Then, is it possible to allocate memory for a char pointer (*name) that is inside a struct (array)?

I don't know what I did wrong, I allocate memory for array, but somehow, I got a Segmentation fault error. The struct with name[200] didn't give me any error. The struct with *name does.

array *str = malloc(sizeof(*str));

Did I miss to allocate something else?

Lord Rixuel
  • 1,173
  • 6
  • 24
  • 43
  • By the way, [you shouldn't cast the result of `malloc()` in C.](http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc) – Iskar Jarak May 23 '15 at 05:13
  • Is it correct if I write `array *str = malloc(sizeof(*str));` instead? – Lord Rixuel May 23 '15 at 05:16
  • Allocate the struct itself first `array *str = malloc(sizeof(array));` and then your string `str->name = malloc(200);` – Algo May 23 '15 at 06:05

3 Answers3

3

Did I miss to allocate something else?

Yes. You allocated memory for an array but not for name inside the array.

You need:

array *str = malloc(sizeof(array));
if ( str == NULL )
{
   // Deal with the error
}

str->name = malloc(200);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Your first allocation method allocates a region of memory with 200 chars as you explicitly code the amount of memory you want. Your second allocation method will only allocate space for the constituent pointer. So allocate the struct first, then allocate space for the constituent pointer explicitly.

array *str = (array*)malloc(sizeof(array));
int n = 200;
str->name = (char*)malloc(sizeof(char)*n);
0

yes you can allocate memory to a char pointer inside an structure

array *str = (array *)malloc(sizeof(array));
if ( str == NULL )
{
   printf("Memory allocation failed \n")
   exit (0);
}
str->name = (char*)malloc(sizeof(char)*200);
if (str->name)
{
   printf("Memory allocation failed \n")
   exit (0);
}
...
//use free() to destroy the memory allocated after use.
free(str->name);   //first destroy the memory for the variable inside the structure
free(str);  //destroy the memory allocated to the object.

than after the use of the pointer '*str' and '*name' use 'free()' to destroy the memory allocated dynamically. First free the '*name' than '*str'.

pradeep bisht
  • 66
  • 1
  • 5