0

I have a char array in typedef struct, which is too big (around 260k)

#define LENGTH 260000

typedef struct {
   int longSize;
   char hello[LENGTH ];
} p_msg;

I would like to use malloc on this char array which as below:

typedef struct {
   int longSize;
   char * hello= malloc(sizeof(char));
} p_msg;

But it gave me error:

error: expected ':', ',', ';', '}' or '__attribute__' before '=' token

How can I malloc the char array?

2
  • If you want the dynamically allocated array to be the same size, you need malloc(LENGTH) instead of malloc(sizeof(char)) (for LENGTH chars, sizeof(char) is always 1), though you can't do it in the type definition like that. Commented Jun 27, 2016 at 2:04
  • I will need to make the LENGTH bigger than that Commented Jun 27, 2016 at 2:13

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I will pass this typedef struct as a param in a function int extMsg( p_msg *msgBuffer); How can I do malloc(sizeof(p_msg))? I'm very new to C. Thanks for the help
1

You need to use pointer types, consider this code:

#include <stdlib.h>
#include <string.h>

typedef struct {
    int longSize;
    char * hello;
} p_msg;

int main()
{
    p_msg msg;
    //zeroing memory to set the initial values
    memset(&msg, 0, sizeof(p_msg));
    //storing the size of char array
    msg.longSize = 260000;
    //dynamically allocating array using stored value
    msg.hello = (char *)malloc(msg.longSize);

    //using msg struct in some function
    int retVal = someFunc(&msg);


    //free hello array after you don't need it
    free(msg.hello);
    msg.hello = 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.