不透明な型を作成しようとしていない限り、構造体にtypedefを使用しないでください。これは間違っています。 struct
は、C開発者にとって大きなヒントです。 Linusはこれについてよく説明していました。
It's a mistake to use typedef for structures and pointers. When you see a
vps_t a;
in the source, what does it mean?
In contrast, if it says
struct virtual_container *a;
you can actually tell what "a" is.
Lots of people think that typedefs "help readability". Not so. They are useful only for:
(a) totally opaque objects (where the typedef is actively used to hide what the object is).
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.
(b) Clear integer types, where the abstraction helps avoid confusion whether it is "int" or "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
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.
(c) when you use sparse to literally create a new type for type-checking.
...
変数の列を連続して宣言しないでください。あなたはそれを行うことによって他人を混乱させるだけです。
もちろん、.
演算子を使用してメンバーフィールドを参照することはできません。->
を使用する必要があります。また、構造体の最初のメンバーとして持つ `単語を考える
#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;
}
かが原因ポインタの位置合わせは整数よりも大きいのプラットフォーム上での位置ずれにメモリを無駄に:それはあなたのコードは次のようになるはずです、言われています。
typedef struct {
int numberOfWords, averageWordLength, id;
char **words;
} sentence;
で
それが仕事に行くのではないの 'S->' ... –
誰もがちょうど「ポインタへのポインタの専門家」ではありません。あなたはCを知っているか、そうではありません。あなたの 'void main'の使用を考えると、おそらくもっと簡単なものから始めることをお勧めします。なぜ 's.'と' s-> 'を混在させるのですか? –
's->' thingyを修正してから、 'sizeof(sentence)'を試してみてください。それと幸運! – alexis