| | |
Malloc a struct
![]() |
•
•
Join Date: Oct 2008
Posts: 5
Reputation:
Solved Threads: 0
Hello guys..
I´m trying to do something like the code below ..
in other words I want to alloc dynamically the number of nodes and also the length of s in node struct
I tried a lot of things like:
and my code do not run
Is it possible to do what I want?
thanks.
I´m trying to do something like the code below ..
c Syntax (Toggle Plain Text)
struct node{ int a; char *s; }; void main() { node *x; int sMAX = 3; int nodeMAX = 10; x = (node*)malloc((sizeof(int)+sizeof(char)*sMAX)*nodeMAX); ... }
I tried a lot of things like:
c Syntax (Toggle Plain Text)
x = (node*)malloc((sizeof(node)*nodeMAX); x = (node*)malloc((sizeof(struct node)*nodeMAX); x = (node*)malloc((sizeof(node)+sizeof(char)*sMAX)*nodeMAX);
Is it possible to do what I want?
thanks.
Last edited by Narue; Nov 21st, 2008 at 11:20 am. Reason: added code tags
>I want to alloc dynamically the number of nodes and also the length of s in node struct
Do it separately:
>Is it possible to do what I want?
In C89, not without invoking undefined behavior. In C99 the "struct hack" has been blessed and is directly supported as a flexible array member:
Do it separately:
c Syntax (Toggle Plain Text)
struct node *x = malloc ( nodeMAX * sizeof *x ); int i; for ( i = 0; i < nodeMAX; i++ ) x->s = malloc ( sMAX );
In C89, not without invoking undefined behavior. In C99 the "struct hack" has been blessed and is directly supported as a flexible array member:
c Syntax (Toggle Plain Text)
struct node{ int a; char s[]; }; struct node *x = malloc ( nodeMAX * ( sizeof *x + sMAX ) );
Last edited by Narue; Nov 21st, 2008 at 1:32 pm.
I'm here to prove you wrong.
![]() |
Similar Threads
- about struct in C (C)
- struct linked list problem (C)
- struct and member function pointer (C)
- Pointers to struct (C++)
- Memory allocation for typedef struct (C++)
Other Threads in the C Forum
- Previous Thread: Sending "char" to "int" variable
- Next Thread: Learning C Language
| Thread Tools | Search this Thread |
#include * ansi array arrays asterisks binarysearch calculate centimeter changingto char character convert copyanyfile copyimagefile copypdffile creafecopyofanytypeoffileinc createprocess() database dynamic execv fflush fgets file floatingpointvalidation fork forloop function getlogicaldrivestrin givemetehcodez grade gtkwinlinux histogram homework i/o ide inches include infiniteloop input interest intmain() iso keyboard km license linked linkedlist linux list looping lowest matrix meter microsoft mysql number oddnumber open opendocumentformat openwebfoundation pdf pointer posix power probleminc process program programming pyramidusingturboccodes radix read recursion recv recvblocked research reversing scheduling segmentationfault send sequential single socket socketprogramming stack standard strchr string suggestions systemcall test threads turboc unix urboc user variable whythiscodecausesegmentationfault win32api windowsapi






