这节目有什么不对?

时间:2011-06-04 12:08:46

标签: c

无法运行此代码...

#include<cstdio>
int main()
{
struct a{
    int b;
    struct a *next;
};

    typedef struct a no;

    no *n;

    n->b = 12;
    n->next = NULL;

    n->next->b = 12;
    n->next->next = NULL;

    printf("%d %d", n->b, n->next->b);
    getchar();
    return 0;
}

6 个答案:

答案 0 :(得分:6)

当你说:

no *n;

你得到一个未初始化的指针。当您使用该指针时,您将获得未定义的行为。

答案 1 :(得分:0)

您为指向结构的指针分配了空间,但您没有为实际结构分配空间。这意味着您没有正在使用的结构的内存地址。

此外,指针指向某个随机内存地址,因为您没有初始化它。因此,您可能会尝试读取和写入不属于您的内存,这可能会导致程序甚至系统崩溃,因为会导致未定义的行为。

答案 2 :(得分:0)

正如@Neil Butterworth所说,你得到一个未经初始化的指针。这意味着此指针可以指向任何位置,从而产生访问冲突错误。解决这个问题的方法很简单,只需在使用该指针之前调用malloc()即可。 malloc()为该指针提供了一个有效且可用的地址,因此没有人会抱怨它。

答案 3 :(得分:0)

您宣布struct INSIDE 是一项功能。

声明该功能的struct OUTSIDE

typedef也应在函数外声明。

#include<cstdio>

struct a{
    int b;
    struct a *next;
};

    typedef struct a no;

int main()
{

 ///... your code...
}

答案 4 :(得分:0)

尝试这样的事情:

no *n = (no*)malloc(sizeof(no));

答案 5 :(得分:0)

#include <cstdio>

/* declaring the struct in the function definition may be possible (I'm not sure,
   actually, haha).  Unless you have a GOOD reason, it's good practice to declare
   structs, globals, typedefs, etc... outside the function */

typedef struct a{
    int b;
    struct a *next;
} no;

int main()
{
    no *n;

    /* Here, you have a pointer.  Remember these are simply (generally) 32-bit values
       defined in your stack space used to store a memory location which points to your
       ACTUAL struct a!  Depending on what USED to be in the stack space, this could
       point ANYWHERE in memory, but usually you will find that it points to the NULL
       memory location, which is just address "0".  To get this to point to something,
       you have to allocate empty space on your heap to store your struct... */

    n = malloc(sizeof(no));

    /* Now your pointer n points to an allocated 'struct a', and you can use it like
       normal */

    n->b = 12;
    n->next = NULL;

    /* You just set n->next, which is another 'no' pointer, to NULL.  This means that
       n->next points nowhere.  So, just like above you have to malloc another instance
       of the struct! */

    n->next = malloc(sizeof(no));

    /* NOW you can use n->next with no ill effects! */

    n->next->b = 12;
    n->next->next = NULL;

    printf("%d %d", n->b, n->next->b);
    getchar();

    /* After you're done with your structs, you want to free them using the POINTERS
       that reference them */

    free(n->next);
    free(n);

    return 0;
}