Pointers: Difference between revisions
wikademia>Gbaor cat. change |
wikademia>Rantir →Advanced Pointers: Added basic example of doing a malloc to a block of memory |
||
| Line 228: | Line 228: | ||
==Advanced Pointers== | ==Advanced Pointers== | ||
This example show how pointers can be used with malloc to point to blocks of memory. | |||
<source lang="c"> | |||
#include <stdlib.h> | |||
#include <stdio.h> | |||
typedef unsigned char uchar; | |||
typedef unsigned int uint; | |||
/* This function shows how to malloc data. It shows that data might | |||
* be zero upon initialization, but it is not guaranteed to be 0. | |||
* */ | |||
void mallocExample(); | |||
void mallocExample() { | |||
/* Using malloc */ | |||
uint size, i; | |||
printf("\n Enter the desired size: "); | |||
scanf("%d", &size); | |||
uchar *data; | |||
/* Check to make sure a NULL pointer wasn't returned from malloc */ | |||
if ((data = (uchar*) malloc(size)) == NULL) | |||
exit(1); | |||
/* Raw data after first malloc. Not guaranteed to be initialized*/ | |||
printf("\n After first malloc"); | |||
for (i = 0; i < size; i++) | |||
printf("\n [%d]: %d", i, data[i]); | |||
/* Fill */ | |||
for (i = 0; i < size; i++) | |||
data[i] = i; | |||
/* After fill */ | |||
printf("\n After fill"); | |||
for (i = 0; i < size; i++) | |||
printf("\n [%d]: %d", i, data[i]); | |||
/* When data is no longer needed it MUST be freed */ | |||
free(data); | |||
if ((data = (uchar*) malloc(size)) == NULL) | |||
exit(1); | |||
/* Raw data after second malloc. Shows how there can be stuff 'left over' | |||
* in memory after malloc call*/ | |||
printf("\n Raw data after malloc"); | |||
for (i = 0; i < size; i++) | |||
printf("\n [%d]: %d", i, data[i]); | |||
free(data); | |||
} | |||
int main(int argc, char **argv) { | |||
mallocExample(); | |||
} | |||
</source> | |||
TODO: | |||
Example:Pointers to structures. | Example:Pointers to structures. | ||
Example: Pointers to void. | Example: Pointers to void. | ||