为什么允许这样的声明?
struct{
    int i;
    char str[]; //一个长度为0的数组?
}
其中的char str[];怎样使用

解决方案 »

  1.   

    char str[]; 申明的应该是一个指向数组的指针
      

  2.   

    这样的声明能通过编译吗?怀疑中……我只知道这样申明是可以的:
    char (*str)[];
    这是一个指向数组的指针
      

  3.   

    刚才我试了一下,只能在struct中这样定义,如果在一个函数中这样定义变量就会出错。
    可能象char str[];这样定义了一个字符数组后,vc会给它一个随机的初始值。
      

  4.   

    可以这样使用:
    int a[4];
    int (*c)[] = (int (*)[])a;类似于:
    int (*cc)[4];
    int a[4];
    cc = &a;
      

  5.   

    Semigod() 说的不对吧?
    这种写法是有问题的
      

  6.   

    在代码中使用char str[]; 的确编译出错。
    但是我说的是放在struct中的情况。
    请问,这样
    struct{
        int i;
        char str[]; //一个长度为0的数组?
    }
    怎样使用struct中的str?
      

  7.   

    struct stu
    {
        int i;
        char str[]; 
    };stu cStr;
    cStr.str;or
    stu pStr;
    pStr = &cStr;
    strcpy(pStr->str,"test");
      

  8.   

    和char * str;是等价的
      

  9.   


    我只知道这样申明是可以的:
    char (*str)[];
    这是一个数组指针
      

  10.   

    在对全体元素赋初值时也可以省去长度说明
    char c[]="BASIC\ndBASE";
    这样是可以的,
      

  11.   

    哈哈,这个我知道,只要你看了《inside C++》就知道,程序员可以用这个struct动态分配自己想要的char的内存大小,是一个小聪明
      

  12.   

    linxy2002(阿郎----酷爱编程) 说的有道理struct stu
    {
    int i;
    char str[]; 
    };int main()
    {
    struct str *p = (str *)malloc(sizeof(stu) + sizeof(char) * 100);  
                                               //多出来的都留给str了。
    strcpy(p->str, "For Test.\n");
    pirntf(p->str);
    }
      

  13.   

    char str[]; 
    不是指长度为0的数组;
    而是指长度为动态的数组,即随着赋值字符串的长度动态变化,但是好像也有个上限
      

  14.   

    struct stu
    {
    int i;
    char str[]; 
    };int main()
    {
    struct str *p = (str *)malloc(sizeof(stu) + sizeof(char) * 100);  
                                               //多出来的都留给str了。
    strcpy(p->str, "For Test.\n");
    pirntf(p->str);
    }是个小技巧,不过好象意义不大啊,而且如pomelowu(羽战士) ( )所说不是每个编译器都支持。
      

  15.   

    To楼上,意义当然是有的啦。str在这里相当于一个指针。我们先看看如果是指针的话,上面我写的程序的两种实现。
    1,
    struct stu
    {
    int i;
    char *str; 
    };int main()
    {
    struct stu *p = (stu *)malloc(sizeof(stu));  
    p->str = (char *)malloc(sizeof(char) * 100);  
    strcpy(p->str, "For Test.\n");
    pirntf(p->str); free(p->str);
    free(p);
    }
    2,
    struct stu
    {
    int i;
    char *str; 
    };int main()
    {
    struct stu *p = (stu *)malloc(sizeof(stu) + sizeof(char) * 100);   p->str = (char *)p + sizeof(stu);
    strcpy(p->str, "For Test.\n");
    pirntf(p->str); free(p);
    }
    再看看这个(把上面我写的代码修正了一下)
    struct stu
    {
    int i;
    char str[]; 
    };int main()
    {
    struct stu *p = (stu *)malloc(sizeof(stu) + sizeof(char) * 100);   strcpy(p->str, "For Test.\n");
    pirntf(p->str); free(p);
    }
    优势还是有的,跟1和2相比,stu结构本身就少了1个指针的空间(Win32 下是4字节)。此外,跟1相比,开辟的是连续空间,而且少进行一套malloc-free操作;根2相比,同样是连续空间,也都只有1套malloc-free操作,但是省去了让指针重定向的操作。这些东西平时可能用不到,也不是所有的编译器都支持,而且还有不小的危险性,但是实用价值也是有的。