Play and learn 300 000+ tabs online

Monday, August 9, 2010

C Malloc multi dimension Dynamic allocation

#include<stdio.h>
int main()
{
char ***p;
int i,j,r,c;
r = 10, c = 12;
p = (char ***) malloc(r * sizeof(char**));
for(i=0;i<r;i++) {
p[i] = (char **) malloc (c * sizeof(char *));
for(j=0;j<c;j++) {
p[i][j] = (char *) malloc(10);
sprintf(p[i][j],"%d:%d",i,j);
printf("%s\t",p[i][j]);
}
printf("\n");
}

// Cleanup
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
free(p[i][j]);
}
free(p[i]);
}
free(p);
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.