需要逻辑来为嵌套结构分配内存

时间:2015-08-05 05:42:49

标签: data-structures linked-list structure

我无法使用指针为嵌套结构分配内存。 我应该使用什么语法为许多具有指向其他结构的指针的结构分配内存?一旦分配了内存,我该如何去访问结构中的值?

struct A {
    int *a;
    struct B *b;
};

struct B {
    int *b;
    struct C *c;
};

struct C {
    int *c;
    struct D *d;
};

struct D {
    int *d;
};

int main(int argc, const char* argv[]) {
    struct A* foo;

    /* Structure allocation */
    /* use of structures */
}

我无法超越2个嵌套结构。除此之外,我开始收到Segmentation故障。

我试过这样的事情:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct file f1;
typedef struct command c1;
typedef struct arguments a1;
typedef struct ccity ccity;
typedef struct csub csub;

struct arguments {
    char *argname;
    struct arguments *next;
};

struct command {
    char *cmdname;
    struct arguments *args;
};

struct file{
    int fileid;
    char *filename;
    struct command *cmd;
};

struct sub{
    char *subname;
};

struct city {
    char *city_name;
    struct sub *s11;
};

struct road{
    char *name;
    struct city *next_city;
};

int main()
{  
    char name[] = "HELLO ";

    struct file *f1;
    struct city *c1 = NULL;
    struct road *r1 = NULL;
    struct sub *s1 = NULL;

    printf("HELOOOOOOOOO");
    f1->filename;
    f1 = malloc(10*sizeof(struct file ));
    f1->filename = (char *)malloc(10*sizeof(char *));
    c1 = malloc(sizeof(c1));
    r1 = malloc(sizeof(r1));
    s1 = malloc(sizeof(s1));

    r1->name = malloc(100*sizeof(char *));
    r1->next_city = malloc(100*sizeof(r1->next_city));

    c1->city_name = malloc(100*sizeof(char *));
    c1->s11 = malloc(100*sizeof(c1->s11));

    c1->s11->subname  = calloc(120,sizeof(char*));
    (*c1).s11->subname = "text";

    (*r1).next_city->s11->subname = 
        malloc(10 * sizeof((*r1).next_city->s11->subname));

    strncpy((*r1).next_city->s11->subname,"sant",4);

    r1->name = malloc(sizeof(char *));
    c1->city_name = malloc(sizeof(char *));

    r1->next_city = malloc(sizeof(char *));
    r1->next_city->city_name = "Hello";

    /*strcpy(f1->filename,"file1");
    printf("name is %s\n",(f1->filename));

    c1->cmdname = (char *)malloc(10*sizeof(c1->cmdname));
    strcpy(f1[0].cmd[0].cmdname,"command1");
    printf("name is %s\n",f1[0].cmd[0].cmdname);

    strcpy(f1[0].cmd[1].cmdname,"command2");
    printf("name is %s\n",f1[0].cmd[1].cmdname);

    strcpy(f1[0].cmd[2].cmdname,"command3");
    printf("name is %s\n",f1[0].cmd[2].cmdname);

    strcpy(f1[0].cmd[2].args[0].argname,"argument1");
    printf("name is %s\n",f1[0].cmd[2].args[0].argname);

    strcpy(f1[0].cmd[2].args[0].argname,"argument1");
    printf("name is %s\n",f1[0].cmd[2].args[1].argname);

    (f1[0].cmd[0].args[0]).argname = malloc(20*sizeof(char*));
    strcpy((f1[0].cmd[0].args[0]).argname,"argument1");

    printf("name is %s\n",(f1[0].cmd[0].args[0]).argname);
    */
}

0 个答案:

没有答案