私はC言語で約1ヶ月間連絡を取っています。構造体とmalloc
の使用法について、より高度な例を得ようとしています。既存のオブジェクトへ行く別の構造体から新しい構造体または既存の構造体にコピー
ウェイに新しいオブジェクト
に
:私は本当に何をしたいのか
は、構造体の要素の深いコピーを作成することです。
メイン1) 1.1_ allocate memory for struct 1.2_ allocate memory for type 1.3_ allocate memory for 2d array data 2) 2.1 free memory of 2d array data with (free) 2.2 free memory of type 2.3 same steps as new object
Element element = initElement();
関数本体に
struct element { char* type; /* 2 charactere*/ int i; int j; int **data;/* 2d array of i and j */ };
ファンクションコール:私は
Element element copyToNewObject (Element _element) { /*No idea how to start */ } Element element copyToExistingObject (Element _element) { /*No idea how to start */ } // Type Element typedef struct element * Element;
私の構造体の要素を作りたいの機能
Element initElement(void) { Element _element = (Element) malloc(sizeof(Element)); int position; if(_element == NULL) { return NULL; } (_element)->type = malloc(2 * sizeof(char)); if((_element)->type == NULL) { return NULL; } element->data = malloc(element->i * sizeof(int *)); if(element->data == NULL) { return NULL; } for(position = 0; position < (element->j) ; position++) (element)->data[position] = malloc((element)->j * sizeof(int)); return _element; }
'initElement'は完全に間違っています。コピーを作ることを心配する前に、私はその権利を得ることに焦点を当てることをお勧めします。私はまた、本や他の参考文献から学ぶことを提案したい。 –
'initElement'関数で、変数' _element'はポインタではありません。これは構造体の*インスタンス*です。これはコンパイラによって割り当てられています。また、文字列は実際には*** null終了**バイト文字列*と呼ばれます。 2文字を含む文字列には、3バイトが割り当てられている必要があります。文字列が*常に*同じサイズを持つ場合、単にそれを文字の配列にするのはなぜですか? –
Cで2次元配列を使いたい場合は、ポインタの配列のmallocと2番目の次元のN mallocの後に、単一の 'malloc()'または 'calloc()'呼び出しを使用します。 –