Created
January 28, 2010 21:29
-
-
Save hlian/289161 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
typedef struct { | |
char *name; | |
int length; | |
} message_t; | |
int main(void) { | |
message_t *messages; | |
int amount = 50; | |
messages = (message_t *) malloc(sizeof(message_t) * amount); | |
/* do stuff here */ | |
free(messages); | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
typedef struct { | |
char *name; | |
int length; | |
} message_t; | |
int main(void) { | |
message_t messages[50]; | |
/* do stuff here */ | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <stdlib.h> | |
typedef struct { | |
char *name; | |
int length; | |
} message_t; | |
/* Dynamically allocates an "amount" amount of messages and | |
returns the pointer. The client must later call | |
messages_free() on the pointer to avoid a memory leak. */ | |
message_t* messages_init(int amount) { | |
message_t *messages = | |
(message_t *) malloc(sizeof(message_t) * amount); | |
assert(messages != NULL); | |
/* Do stuff here, if you want */ | |
return messages; | |
} | |
/* Frees the messages allocated by messages_init(). Every | |
messages_init() call needs to be paired with a | |
messages_free() call. */ | |
void messages_free(message_t *messages) { | |
free(messages); | |
} | |
int main(void) { | |
message_t *messages = messages_init(50); | |
int i; | |
for (i = 0; i < 50; i++) { | |
message_t *message = &messages[i]; | |
message->length = 10; | |
/* Other stuff */ | |
} | |
free_messages(messages); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment