无法创建链接列表

时间:2018-02-23 01:26:55

标签: c arrays linked-list

对于模糊的标题感到抱歉,我不太清楚如何解释发生了什么。我试图创建一个链表,链表的每个条目包含两个字符串,一个可以容纳四个条目的整数数组,以及一个可以容纳四个条目的浮点数组。 这是头文件中主结构的初始化 -

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#define MAX_LENGTH  20

struct stock {
char ticker[MAX_LENGTH];
char comp[MAX_LENGTH];
int shares[4];
float price[4];
struct stock *next;
};

#endif

以下是我的主文件中的代码 -

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "functions.h"


void main(void) {

int choice,shr[4], i;
char tic[MAX_LENGTH];
char nam[MAX_LENGTH];
float pri[4];

struct stock *head = NULL;// entry point for linked list
struct stock *current; //pointer currently being used

printf("Press 1 to enter a new stock\n");
printf("Press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
    printf("Enter the stock ticker:\n");
    scanf("%s", &tic);
    printf("Enter the name of the stock:\n");
    scanf("%s", &nam);

    for(i = 1; i<=4; i++) {
    printf("Enter the number of shares:\n");
    scanf("%d",&shr[i] );
    printf("Enter the price of the stock:\n");
    scanf("%f", &pri[i]);
    }

    if(head == NULL) { //check to see if first element has been filled
        head = (struct stock *)malloc(sizeof(struct stock));
        current = head;
    }
    else { //if the first element is full, move on to the next entry
        current->next = (struct stock *)malloc(sizeof(struct stock));
        current = current->next;
    }

    strcpy(current->ticker, tic);
    strcpy(current->comp, nam);
    memcpy(current->shares, shr, sizeof(current->shares));
    memcpy(current->price, pri, sizeof(current->price));
    current->next = NULL;


}
printf("%s\n", current->ticker);
printf("%s\n", current->comp);

for(i = 1; i <= 4; i++) {
    printf("%d\n", current->shares[i]);
    printf("%f\n", current->price[i]);
}
}

该计划的最终目标是拥有两个单独的库存条目,并能够根据每种库存的四种不同份额购买计算FIFO / LIFO美元成本平均值。但就目前而言,我只是试图将信息正确地输入到链表中。

在循环向用户询问股票数量和股票价格四次后,字符串&#34; nam&#34;之前的要求似乎消失了,因为如果我试图访问它或打印出来以后它什么都不打印。

我正在尝试使用memcpy函数将输入的数组复制到链表中的数组。每当我将数组复制到链表后尝试将数组打印出来时,它都无法正确打印。股票和价格数组的前三个条目打印正确,但第四个共享条目打印一个巨大的数字,第四个浮动条目打印为零。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

ticnam已经是指针,所以更改

scanf("%s", &tic);
scanf("%s", &nam);

scanf("%s", tic);
scanf("%s", nam);

此外,与您的问题没有直接关系,但

head = (struct stock *)malloc(sizeof(struct stock));
current->next = (struct stock *)malloc(sizeof(struct stock));

会更好地写成

head = malloc(sizeof(*head));
current->next = malloc(sizeof(*(current->next)));

无需从malloc()转换回报,并且使用sizeof(*head)保证您使用sizeof的正确类型。

相关问题