Skip to content

Instantly share code, notes, and snippets.

@shichao-an
Last active April 15, 2016 06:59
Show Gist options
  • Save shichao-an/b735bc3a6f42eecd4802fad3f677511a to your computer and use it in GitHub Desktop.
Save shichao-an/b735bc3a6f42eecd4802fad3f677511a to your computer and use it in GitHub Desktop.
Flexible array member
#include <stdio.h>
#include <stdlib.h>
typedef struct string
{
int length;
char chars[];
} string;
int main(int argc, char * argv[])
{
int len = sizeof(string) + 10;
char buf[len];
string *s = (string*)buf;
s->length = 9;
strcpy(s->chars, "123456789");
printf("%d\n%s\n", s->length, s->chars);
return EXIT_SUCCESS;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct string
{
int length;
char chars[];
} string;
int main(int argc, char * argv[])
{
int len = sizeof(string) + 10;
char buf[len];
string *s = (string*)buf;
s->length = 10;
strcpy(s->chars, "123456789");
string s2 = *s; // copy struct string s
printf("%d\n%s\n", s2.length, s2.chars); // s2.length is copied, s2.chars is not
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment