Allocating works the same for all types. If you need to allocate an array of line structs, you do that with:

struct line* array = malloc(number_of_elements * sizeof(struct line));

In your code, you were allocating an array that had the appropriate size for line pointers, not for line structs. Also note that there is no reason to cast the return value of malloc().

Note that's it's better style to use:

sizeof(*array)

instead of:

sizeof(struct line)

The reason for this is that the allocation will still work as intended in case you change the type of array. In this case this is unlikely, but it's just a general thing worth getting used to.

Also note that it's possible to avoid having to repeat the word struct over and over again, by typedefing the struct:

typedef struct line
{
    char* addr;
    char* inst;
} line;

You can then just do:

line* array = malloc(number_of_elements * sizeof(*array));

Of course don't forget to also allocate memory for array.addr and array.inst.

Answer from Nikos C. on Stack Overflow
Top answer
1 of 2
37

Allocating works the same for all types. If you need to allocate an array of line structs, you do that with:

struct line* array = malloc(number_of_elements * sizeof(struct line));

In your code, you were allocating an array that had the appropriate size for line pointers, not for line structs. Also note that there is no reason to cast the return value of malloc().

Note that's it's better style to use:

sizeof(*array)

instead of:

sizeof(struct line)

The reason for this is that the allocation will still work as intended in case you change the type of array. In this case this is unlikely, but it's just a general thing worth getting used to.

Also note that it's possible to avoid having to repeat the word struct over and over again, by typedefing the struct:

typedef struct line
{
    char* addr;
    char* inst;
} line;

You can then just do:

line* array = malloc(number_of_elements * sizeof(*array));

Of course don't forget to also allocate memory for array.addr and array.inst.

2 of 2
10

For what you have described, You do not need to allocate memory for your struct, rather, you need to allocate memory for the members char *addr;, and char *inst;. If you want to have a single copy of that structure, the first section of code illustrates how to initialize, and assign values. If you want an array, the second code example illustrates the differences.

This illustrates how to allocate memory for the members of a single struct line:

typedef struct
{
    char* addr;
    char* inst;
}LINE;

LINE line;  

int main(void)
{   

    strcpy(line.addr, "anystring"); //will fail
    line.addr = malloc(80);
    line.inst = malloc(80);
    strcpy(line.addr, "someString");//success;
    strcpy(line.inst, "someOtherString");//success;

}

For array of struct line...

typedef struct
{
    char* addr;
    char* inst;
}LINE;  //same struct definition

LINE line[10]; //but create an array of line here.

int main(void)
{   
    int i;
    
    for(i=0;i<10;i++)
    {
      line[i].addr = malloc(80);
      line[i].inst = malloc(80);
    }

    for(i=0;i<10;i++)
    {
        strcpy(line[i].addr, "someString");
        strcpy(line[i].inst, "someOtherString");
    }
    //when done, free memory
    for(i=0;i<10;i++)
    {
        free(line[i].addr);
        free(line[i].inst);
    }      


}

Added to address comment
Addressing the comment under this answer from @Adam Liss, the following code illustrates the following improvements using strdup(): 1) Uses only memory needed. 2) Performs memory creation and copy operations in one step, so the the following blocks:

for(i=0;i<10;i++)
{
  line[i].addr = malloc(80);
  line[i].inst = malloc(80);
}

for(i=0;i<10;i++)
{
    strcpy(line[i].addr, "someString");
    strcpy(line[i].inst, "someOtherString");
}

Become:

for(i=0;i<10;i++)
{
  line[i].addr = strdup("someString");
  line[i].inst = strdup("someOtherString");
}

One more note: Error handling was not included in examples above to avoid muddling up focus on the main concepts: But for the sake of completeness, because both malloc() and strdup() can fail, actual usage for each of these two functions, should include a test before using, eg:

Rather than

  line[i].addr = strdup("someString");
  line[i].inst = strdup("someOtherString");

The code should include

  line[i].addr = strdup("someString");
  if(!line[i].addr)
  {
      //error handling code here
  }
  line[i].inst = strdup("someOtherString");
  if(!line[i].inst)
  {
      //error handling code here
  }
🌐
Stack Overflow
stackoverflow.com › questions › 22390713 › char-malloc-and-struct-arrays
Char, Malloc, and Struct Arrays - Stack Overflow
Allocate 20 bytes for each of the index, as you mentioned: for (i=0;i<20;i++) { info->name[i]=(char *)malloc(sizeof(char)*20); } Also, you are treating your struct pointer info as an array:
Discussions

Memory allocation for char array inside struct
My question is, do I need to allocate memory for the char pointer name of the struct or is the assignment of this->name enough? Depends on what you want to do. If you simply assign to this->name, then the object you've just allocated won't "own" the pointer or the contents of the string to which it points. It has merely borrowed the pointer. The string contents could change at any time, or the pointer could be invalidated by being freed, without the Human object even knowing. Borrowing pointers can indeed be useful in some cases, but it's almost certainly not what you want here. You probably want to strdup the name argument to create a completely new string with the same contents. You might even want to change name to be a const char *, to emphasise the fact that the value being passed is going to be copied, not borrowed. If you do create a whole new string for that name field, you will probably want to provide a destructor for your Human objects, e.g.: void human_free(Human *this) { free(this->name); free(this); } Also, on a completely different note, the cast in: Human *this = (Human *) malloc(sizeof(Human)); isn't necessary in C. Object pointers can be converted to and from void pointers without casts. More on reddit.com
🌐 r/C_Programming
29
25
July 28, 2018
c - Allocating char array using malloc - Stack Overflow
Yes, it's a matter of style, because you'd expect sizeof(char) to always be one. On the other hand, it's very much an idiom to use sizeof(foo) when doing a malloc, and most importantly it makes the code self documenting. More on stackoverflow.com
🌐 stackoverflow.com
c - Allocate memory for char array pointer of struct inside function - Stack Overflow
I was looking around for about one day on how to solve my problem. I find solutions for problems similar to mine but when I apply changes error : error: request for member 'mark' in something not a More on stackoverflow.com
🌐 stackoverflow.com
c - malloc an array of struct pointers - Stack Overflow
I have the following struct: typedef struct _chess { int **array; int size; struct _chess *parent; } chess; and I have: typedef struct _chess *Chess; Now, I want to create an array of dy... More on stackoverflow.com
🌐 stackoverflow.com
September 9, 2015
🌐
Reddit
reddit.com › r/c_programming › memory allocation for char array inside struct
r/C_Programming on Reddit: Memory allocation for char array inside struct
July 28, 2018 -

Hey friends,

I'm sure somebody on the internet jas alread answered this, but I honestly haven't found a suitable answer for me.

Let's say we have a struct like this:

typedef struct {
    char *name;
    int age;
} Human;

And a kind of "constructor" function like this:

Human *human_new(char *name, int age)
{
    Human *this = (Human *) malloc(sizeof(Human));

    this->name = name;
    this->age  = age;

    return this;
}

My question is, do I need to allocate memory for the char pointer name of the struct or is the assignment of this->name enough?

Top answer
1 of 5
25
My question is, do I need to allocate memory for the char pointer name of the struct or is the assignment of this->name enough? Depends on what you want to do. If you simply assign to this->name, then the object you've just allocated won't "own" the pointer or the contents of the string to which it points. It has merely borrowed the pointer. The string contents could change at any time, or the pointer could be invalidated by being freed, without the Human object even knowing. Borrowing pointers can indeed be useful in some cases, but it's almost certainly not what you want here. You probably want to strdup the name argument to create a completely new string with the same contents. You might even want to change name to be a const char *, to emphasise the fact that the value being passed is going to be copied, not borrowed. If you do create a whole new string for that name field, you will probably want to provide a destructor for your Human objects, e.g.: void human_free(Human *this) { free(this->name); free(this); } Also, on a completely different note, the cast in: Human *this = (Human *) malloc(sizeof(Human)); isn't necessary in C. Object pointers can be converted to and from void pointers without casts.
2 of 5
5
Yes, you will need to allocate memory for whatever you want to put in the name of the struct. malloc(sizeof(Human)) will allocate enough space for a char pointer and an int, it won't allocate memory for the contents of name because it has no idea what the size will be. If you know the upper bound on the size of name, or are happy to enforce one, you could change the definition of the struct to: typedef struct { char name[100]; int age; } Human; Then when you call malloc(sizeof(Human)) you'll get enough space for a 'string' containing up to 100 characters (only 99 usable because of the null terminator) and an int. If you do that, it would probably be sensible to define the maximum length of a name as #define MAX_HUMAN_NAME_LENGTH 100 to be clearer and so you only have to change it in one place.
🌐
Linux Hint
linuxhint.com › array-of-structs-malloc
How to Use Malloc Function to Create Array of Structs – Linux Hint
Then in the main function, we passed the argc(argument count) and argv(argument vector) used for the numbers which are input by the users and point to the character pointers respectively · After this, we have declared the struct of “Employees” having two values emp_id and emp_name · Initialized the two variables num and i; num has assigned the value of 2 so that it can take two inputs for struct “Employees” · Then used the malloc function to assign the memory according to the value of num to the pointer array (Employees)
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 52608-how-malloc-char-**.html
How to malloc (char **)
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Words { char **wordList; }; int main(void) { int i, listCount = 4; char words[5][25] = {"Season", "Fan", "Car", "Fruit"}; struct Words filter; filter.wordList = malloc(listCount * sizeof *filter.wordList); if ( filter.wordList ...
Find elsewhere
🌐
CopyProgramming
copyprogramming.com › howto › how-to-malloc-a-char-array-in-c
Char: Creating a char array using malloc in the C programming language
May 8, 2023 - Memory - malloc vs array in C, ... want a single pointer to a character, you should use a string instead. typedef struct{ char *name ; } arr; arr thisOne; thisOne.name = malloc(sizeof(char) * 128);...
🌐
Delft Stack
delftstack.com › home › howto › c malloc struct
How to Allocate Struct Memory With malloc in C | Delft Stack
February 12, 2024 - It’s a basic example showcasing how to dynamically allocate memory for a struct, access its members, perform operations, and release the allocated memory to prevent memory leaks. It’s often useful to declare an array of structures, which may require a larger memory region than available on the stack. Thus, we need to allocate the array as dynamic memory. In this method, memory is allocated to store an array of structures using malloc...
🌐
Dartmouth College
cs.dartmouth.edu › ~campbell › cs50 › dynamicmem.html
Pointers and Dynamic Memory Allocation
In the previous examples the data type pointed to was a char - which is a byte (8 bits) in terms of strorage. So p++ (where char *p) increments by obe byte of 8 bits. But what happens if the pointer p points to a structure? ... /* File: pointers.c Description: Creates an array of struct types.
🌐
Nyu-cso
nyu-cso.github.io › notes › 06-struct-malloc.pdf pdf
Struct, malloc Jinyang Li
– C has no support for object oriented programming · – You can view structs as rudimentary “objects” · without associated member functions · Define and access struct · struct student { int id; char *name; }; struct student t; define variable t with ·
🌐
UCSD
cseweb.ucsd.edu › ~j2lau › cs5a › week8.html
Week 8: structs, malloc
February 25, 2002 - /* malloc a double */ double* dp = (double*) malloc(sizeof(double)); /* malloc an item */ struct item* ip = (struct item*) malloc(sizeof(struct item)); /* * malloc an array of 50 integers - the name of an array is always * a pointer to the first element of the array */ int* array = (int*) malloc(50 ...
🌐
Swarthmore College
cs.swarthmore.edu › ~newhall › cs31 › resources › C-structs_pointers.php
CS31: Intro to C Structs and Pointers
malloc is often used to allocate an array of some type on the heap, by specifying the total number of bytes in the array using an expression of (size of the type of each bucket and the number of buckets: int *arr; char *c_arr; // allocate an array of 20 ints on the heap: arr = (int ...
Top answer
1 of 4
49

array is a slightly misleading name. For a dynamically allocated array of pointers, malloc will return a pointer to a block of memory. You need to use Chess* and not Chess[] to hold the pointer to your array.

Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;

and perhaps later:

/* create new struct chess */
array[i] = malloc(sizeof(struct chess));

/* set up its members */
array[i]->size = 0;
/* etc. */
2 of 4
23

There's a lot of typedef going on here. Personally I'm against "hiding the asterisk", i.e. typedef:ing pointer types into something that doesn't look like a pointer. In C, pointers are quite important and really affect the code, there's a lot of difference between foo and foo *.

Many of the answers are also confused about this, I think.

Your allocation of an array of Chess values, which are pointers to values of type chess (again, a very confusing nomenclature that I really can't recommend) should be like this:

Chess *array = malloc(n * sizeof *array);

Then, you need to initialize the actual instances, by looping:

for(i = 0; i < n; ++i)
  array[i] = NULL;

This assumes you don't want to allocate any memory for the instances, you just want an array of pointers with all pointers initially pointing at nothing.

If you wanted to allocate space, the simplest form would be:

for(i = 0; i < n; ++i)
  array[i] = malloc(sizeof *array[i]);

See how the sizeof usage is 100% consistent, and never starts to mention explicit types. Use the type information inherent in your variables, and let the compiler worry about which type is which. Don't repeat yourself.

Of course, the above does a needlessly large amount of calls to malloc(); depending on usage patterns it might be possible to do all of the above with just one call to malloc(), after computing the total size needed. Then you'd still need to go through and initialize the array[i] pointers to point into the large block, of course.

🌐
W3Schools
w3schools.com › c › c_memory_struct.php
C Structures and Dynamic Memory
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Car { char brand[50]; int year; }; int main() { int count = 2; struct Car *cars = (struct Car*) malloc(count * sizeof(struct Car)); if (cars == NULL) { printf("Initial allocation ...
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Dynamically Allocate Memory For An Array Of Chars - Programming - Arduino Forum
December 29, 2022 - I'm trying to create dynamic array of strings, but obviously I'm missing something... This does not compile: char **AOC; AOC = malloc(20 * sizeof(char *)); AOC[0] = malloc(20 * sizeof(char)); with this error: AOC = ma…
🌐
Quora
quora.com › How-do-I-malloc-an-array-of-structs-in-C
How to malloc() an array of structs in C - Quora
Then, [code]struct X *pArray = malloc(sizeof(struct X) * N); if (pArray) { // Access elements using pArray } [/code]It’s really that simple. You can use pArray with square bracket ...
🌐
Diveintosystems
diveintosystems.org › book › C2-C_depth › structs.html
Dive Into Systems
In examining the last example, start by considering the type of the outermost variable (p2 is a pointer to a struct personT). Therefore, to access a field value in the struct, the programmer needs to use → syntax (p2→name). Next, consider the type of the name field, which is a char *, used in this program to point to an array of char values.