's'的存储大小未知+指针指针

Nay*_*yef 1 c malloc struct pointers

问候,我遇到了错误"Assignment_1.c:10:18:错误:'s的存储大小'未知"我不是使用指针指向的专家,我想要一个动态大小的动态大小的数组话.任何的想法?

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int size = MAX;
typedef struct{
    int numberOfWords,averageWordLength,id;
    char ** words;      
    }sentence;
void main(){  
    struct sentence s; 
    s.numberOfWords=3;
    s.averageWordLength=5;
    s.id=1;
    s->words= malloc(size * sizeof(s));
    //printf("%s",s.words);
    }
Run Code Online (Sandbox Code Playgroud)

小智 7

除非您尝试创建opaque类型,否则不要对结构使用typedef.这是错的.struct对C开发人员来说是一个很好的暗示.Linus对此有一个很好的描述:

将typedef用于结构和指针是错误的.当你看到一个

vps_t a;

在源头,这是什么意思?

相反,如果它说

struct virtual_container*a;

你实际上可以告诉"a"是什么.

很多人认为typedef"有助于提高可读性".不是这样.它们仅适用于:

(a)完全不透明的对象(其中typedef主动用于 隐藏 对象的内容).

 Example: "pte_t" etc. opaque objects that you can only access using
 the proper accessor functions.

 NOTE! Opaqueness and "accessor functions" are not good in themselves.
 The reason we have them for things like pte_t etc. is that there
 really is absolutely _zero_ portably accessible information there.
Run Code Online (Sandbox Code Playgroud)

(b)清除整数类型,其中抽象有助于避免混淆,无论它是"int"还是"long".

 u8/u16/u32 are perfectly fine typedefs, although they fit into
 category (d) better than here.

 NOTE! Again - there needs to be a _reason_ for this. If something is
 "unsigned long", then there's no reason to do
Run Code Online (Sandbox Code Playgroud)

typedef unsigned long myflags_t;

 but if there is a clear reason for why it under certain circumstances
 might be an "unsigned int" and under other configurations might be
 "unsigned long", then by all means go ahead and use a typedef.
Run Code Online (Sandbox Code Playgroud)

(c)当你使用sparse从字面上创建一个类型进行类型检查时.

...

不要连续声明一堆变量.你这样做只会让别人感到困惑.

当然,您不能使用.运算符引用成员字段,您必须使用->.话虽这么说,您的代码应该类似于:

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

#define MAX 100

struct sentence {
    int numberOfWords;
    int averageWordLength;
    int id;
    char **words;
};

int main()
{
    struct sentence s;
    s.numberOfWords = 3;
    s.averageWordLength = 5;
    s.id = 1;
    s.words = malloc(MAX * sizeof(s));
    /* printf("%s",s.words); */
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

还要考虑将`words作为结构的第一个成员,或者由于指针对齐大于整数的平台上的错位而浪费内存.