C言語 連結リストのchar要素
解決したいこと
C言語で連結リストを使用して自動販売機システムを書いており、要素に文字列を含めているのですが、データを追加していくとすべてのセルの文字列要素が同じ文字列になってしまいます。どうしたら解決できるでしょうか。ポインタの指定の仕方がおかしいのでしょうか。
発生している問題・エラー
=====メニュー=====
1.牛乳.....90円
2.牛乳.....120円
3.牛乳.....150円
該当するソースコード
main()関数内
List* Drink = make_list();//ドリンクの在庫リストを作成
strcpy_s(&temp_name, 20, "お茶");
push(Drink,10,150,&temp_name);
strcpy_s(&temp_name, 20, "コーヒー");
push(Drink, 0, 120, &temp_name);
strcpy_s(&temp_name, 20, "牛乳");
push(Drink,10,90,&temp_name);
連結リストに用いる関数
// セル
typedef struct cell {
int stock;//残数
int value;//値段
char *name;//名前
struct cell* next;
} Cell;
// リスト
typedef struct {
Cell* top;
} List;
// セルの生成
Cell* make_cell(int sto,int val,char *nam, Cell* cp)
{
Cell* newcp = malloc(sizeof(Cell));
if (newcp != NULL) {
newcp->stock = sto;
newcp->value = val;
newcp->name = nam;
newcp->next = cp;
}
return newcp;
}
// リストの生成
List* make_list(void)
{
List* ls = malloc(sizeof(List));
if (ls != NULL) {
ls->top = make_cell(0, 0,NULL,NULL); // ヘッダセルをセット
if (ls->top == NULL) {
free(ls);
return NULL;
}
}
return ls;
}
//n 番目の位置にデータを挿入する
bool insert_nth(List* ls, int n, int x,int y,char* z)
{
Cell* cp = nth_cell(ls->top, n - 1);
if (cp == NULL) return false;
cp->next = make_cell(x,y,z, cp->next);
return true;
}
// 先頭に追加
bool push(List* ls, int x,int y,char* z)
{
return insert_nth(ls, 0, x,y,z);
}
0 likes