how to use malloc () in Double Pointer in Structure in C -
i have structs:
typedef struct accont { char **tel;//list of tel char **email;//list of emails }acc;
and
typedef struct _strcol { int count; //total of accounts acc **list; } strcol ;
i access structure pointer:
strcol index; contato *p; p = (index.list + index.count);
the question, how use malloc() in function?
i try:
(*p)->tel = (char **) malloc(i * sizeof (char*)) p.tel = (char **) malloc(i * sizeof (char*)) &(*p)->tel = (char **) malloc(i * sizeof (char*))
and second malloc save data email or tel
my first post, excuse anything
i'm going assume 'p' acc *p; (i have no idea 'contato' is). anyway ... point show how memory can allocated & tel/email data stored/accessed ... copied tel #/email id demonstrate ... regarding casting void pointer returns malloc, i've seen arguments for/against ... cast (malloc's case cast).
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct accont { char **tel; //list of tel char **email; //list of emails }acc; typedef struct _strcol { int count; //total of accounts acc **list; }strcol; int main() { int inumaccounts = 5; // assume there 5 accounts. int inumtels = 2; // each account has 2 tel #s. int inumemails = 3; // each account has 3 email ids. strcol index; acc *p = null; index.list = (acc **)malloc(5 * sizeof(acc *)); // master list // of 'acc' pointers i.e. pointer set of pointers. int i, j; for(i=0; i<inumaccounts; i++) // go through 5 accounts, 1 @ // time ... , allocate & store tel #s/email ids. { index.list[i] = (acc *)malloc(sizeof(acc)); p = index.list[i]; p->tel = (char **)malloc(inumtels * sizeof(char*)); for(j=0; j<inumtels; j++) { p->tel[inumtels] = (char *)malloc(11 * sizeof (char)); // 10 digit tel # + 1 byte '\0' ... strcpy(p->tel[inumtels], "1234567890"); } p->email = (char **)malloc(inumemails * sizeof(char*)); for(j=0; j<inumemails; j++) { p->email[inumemails] = (char *)malloc(51 * sizeof(char)); // 50 char long email id + 1 byte '\0' ... strcpy(p->email[inumemails], "kingkong@ihop.yum"); } } for(i=0; i<inumaccounts; i++) // go through 5 accounts, 1 @ time ... , display. { p = index.list[i]; for(j=0; j<inumtels; j++) { printf("tel # is: %d\n", p->tel[inumtels]); } for(j=0; j<inumemails; j++) { printf("email id is: %s\n", p->email[inumemails]); } printf("----------\n"); } }
Comments
Post a Comment