構造体のメンバ変数を2つの異なる関数save_struct_model_1
とsave_struct_model_2
で出力しようとしています。両方とも正常に動作し、正しい値を出力するようです。これらのうちどれが正しいか、好ましいか。Cの構造ポインタ
#include <stdio.h>
#include <stdlib.h>
struct model{
char *name;
int year;
};
void save_struct_model_1(struct model *s){
printf("%s ", s->name);
printf("%d \n",s->year);
}
void save_struct_model_2(struct model s){
printf("%s ", s.name);
printf("%d \n",s.year);
}
int main()
{
typedef struct model M;
M * honda = (M *) malloc (sizeof(M));
honda->name="civic";
honda->year=2000;
save_struct_model_1(honda);
save_struct_model_2(*honda);
return 0;
}
秒1つのコピー '* honda'からの一時的な値と、元の構造体を変更することはできません。 –
ありがとう@BlagovestBuyukliev、 – marc
ほとんどの場合、 'model_1'が好まれます。あなたが印刷しているだけの場合は、 'void save_struct_model_1(const struct model * s);を使ってください。' struct model {int x [1000000000]; }; '次に、4GB +をスタックにプッシュします。各コールでパフォーマンスのペナルティはもちろん、スタックを爆破します。そのため、structポインタを渡すのがその理由です。 35年以上のCを経て、モデル2を使用する機会は一度もありませんでした。 –