You can't call a function from within a struct definition. You should instead simply keep your first struct definition with the large string inside, and then do malloc(sizeof(p_msg)) when you want to create one.

Or you can keep it with the pointer inside, and remember to initialize that pointer with the result of malloc() every time you create a struct instance.

If you have a function taking the struct by pointer, you can do this:

int extMsg(p_msg *msgBuffer)
{
    msgBuffer->longSize = 12;
    msgBuffer->hello = malloc(12);
    snprintf(msgBuffer->hello, 12, "hello %d", 42);
    return 0;
}
Answer from John Zwinck on Stack Overflow
🌐
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.
Discussions

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
Char, Malloc, and Struct Arrays - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Im still learning C and I have a question regarding char arrays, malloc and structures. More on stackoverflow.com
🌐 stackoverflow.com
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 - Malloc an array inside a struct - Stack Overflow
I'm trying to malloc an array inside a struct but I keep getting segmentation errors when I run the program. The compares function is just something I'm testing so it shouldn't be a part of the pr... More on stackoverflow.com
🌐 stackoverflow.com
May 19, 2015
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
  }
🌐
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() { int l; int listCount = 4; char words[5][25] = {"Season", "Fan", "Car", "Fruit"}; Words *filter; filter = (Words*) malloc ( sizeof(Words) ); // Write bad words to char array for (l = 0; l < listCount; l++) { filter->wordList[l] = (char *) malloc (strlen(words[l]) + 1); strcpy( filter->wordList[l], words[l] ); } printf("%s\n", filter->wordList[0]); for (l = 0; l < listCount; l++) { free((char *)filter->wordList[l]); } free((Words*)filter); return 0; } I'm trying to stay away from using an array of any sort like a char *[], I was just hoping there was a way to allocate memory to a (char **).
🌐
Linux Hint
linuxhint.com › array-of-structs-malloc
How to Use Malloc Function to Create Array of Structs – Linux Hint
An array of a struct can be declared ... the array of structs using the malloc() function. The structs in C programming are used similarly to classes. The execution time of the structs is relatively faster than the classes. To understand the struct, consider the example: We have a struct of ...
🌐
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: ... You can't do this, because: info->count is not ...
🌐
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, ... follows char *x = malloc (10*sizeof (char)). To free the memory one would use free (x). But there is another way to … ... The variable name holds an array of pointers to characters. If you 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);...
Find elsewhere
🌐
Quora
quora.com › How-do-I-dynamically-allocate-a-char-array-using-a-malloc-function-in-C
How to dynamically allocate a char array using a malloc function in C - Quora
In order to allocate memory dynamically using C language the following code will be enough: char *s = (char *)malloc(20 * sizeof(char)); The above line allocates memory for storing 20 characters or in fact 19 ch...
🌐
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 i...
🌐
Nyu-cso
nyu-cso.github.io › notes › 07-structs_malloc_2d.pdf pdf
Strings, Structs, malloc, 2D arrays Jinyang Li
• ASCII Characters · Today · • strings · • structs, malloc, 2D array · C Strings · Strings · • String is represented as an array of chars. – Array has no space to encode its length. • How to determine string length? – possible solu<on: explicitly pass an int represen<ng length ·
🌐
Diveintosystems
diveintosystems.org › book › C2-C_depth › structs.html
2.7. C Structs
In examining the last example, ... 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....
🌐
Dartmouth College
cs.dartmouth.edu › ~campbell › cs50 › dynamicmem.html
Pointers and Dynamic Memory Allocation
We have discuss pointers and we have looked at simple allocation of arrays using dynamic memory. Note that malloc (which we will use through the course) returns a “pointer to void” (void *) allowing the returning pointer to be “cast” to any data structure.
🌐
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 ...
🌐
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…
🌐
LabEx
labex.io › tutorials › c-how-to-manage-memory-for-char-types-in-c-510337
How to manage memory for char types in C | LabEx
typedef struct { char* buffer; size_t size; size_t used; } MemoryArena; MemoryArena* create_memory_arena(size_t initial_size) { MemoryArena* arena = malloc(sizeof(MemoryArena)); arena->buffer = malloc(initial_size); arena->size = initial_size; arena->used = 0; return arena; } char* arena_allocate(MemoryArena* arena, size_t size) { if (arena->used + size > arena->size) { return NULL; } char* result = arena->buffer + arena->used; arena->used += size; return result; }