Skip to content

Instantly share code, notes, and snippets.

@maluta
Created April 1, 2010 13:20
Show Gist options
  • Save maluta/351784 to your computer and use it in GitHub Desktop.
Save maluta/351784 to your computer and use it in GitHub Desktop.
/*
This was discussed in http://www.c-faq.com/struct/structhack.html
Despite its popularity, the technique is also somewhat notorious:
Dennis Ritchie has called it ``unwarranted chumminess with the C implementation,''
and an official interpretation has deemed that it is not strictly conforming with
the C Standard, although it does seem to work under all known implementations.
(Compilers which check array bounds carefully might issue warnings.)
gcc -o structhack -Wall -ggdb structhack.c
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct name {
int namelen;
char namestr[1];
};
int main(int argc, char *argv[]) {
char *newname="www.coding.com.br";
struct name *ret = malloc(sizeof(struct name)-1 + strlen(newname)+1);
if (ret != NULL) {
ret->namelen = strlen(newname);
strcpy(ret->namestr,newname);
}
printf("%s \n",ret->namestr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment