2

If I have a struct defined as such:

typedef struct{

    char a[];

}my_struct_t;

How do you allocate memory for a string with malloc() such that it is stored in my_struct_t?

1
  • 1
    That looks suspiciously like char * with a funny type. Commented Oct 6, 2016 at 19:12

2 Answers 2

4

Code could use a flexible array member FAM to the store string in the structure. Available since C99. It requires at least one more member in the struct than OP's code.

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. ... C11 §6.7.2. 18

typedef struct fam {
  size_t sz;  // At least 1 member. 
  char a[];   // flexible array member - must be last.
} my_struct_t;

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

my_struct_t *foo(const char *src) {
  size_t sz = strlen(src) + 1;

  // Allocate enough space for *st and the string.
  // `sizeof *st` does not count the flexible array member. 
  struct fam *st = malloc(sizeof *st + sz);
  assert(st);

  st->sz = sz;
  memcpy(st->a, src, sz);
  return st;
}

As exactly coded, the below is not valid C syntax. Of course various compilers offer language extensions.

typedef struct{
    char a[];
}my_struct_t;
Sign up to request clarification or add additional context in comments.

3 Comments

Something about this seems dangerous. I have never seen it before. Very interesting.
@Secto Kia Older C would use the last member as char a[1]; so the technique has been used for decades. That older technique had issues that are satisfied with C99 and char a[]; ( alignment, sizeof struct, analysis tools). Like many tools in the C shed: use the right tool for the right job.
@SectoKia Note: often malloc(sizeof *st + sizeof *(st->a) * N); idiom is used when the last array element is not char [].
2
#include <stdio.h>
#include <stdlib.h>

typedef struct {
     char* a;
} my_struct_t;


int main() 
{
    my_struct_t* s = malloc(sizeof(my_struct_t));
    s->a = malloc(100);
    // Rest of Code
    free(s->a);
    free(s);
    return 0;
}

Array of 100 chars.

1 Comment

OP requested "...allocate memory for a string with malloc such that it is stored in my_struct_t?" . This answer likely meets OP's goal, yet it does not store the string in the structure, but stores a pointer to the future string.

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.