【问题标题】:Having trouble creating a linked list创建链接列表时遇到问题
【发布时间】:2018-02-23 01:26:54
【问题描述】:

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

#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 美元成本平均值。但是现在,我只是想能够正确地将信息输入到链表中。

在四次询问用户股票数量和股票价格的循环之后,之前询问的字符串“nam”似乎消失了,因为如果我稍后尝试访问或打印它什么都不打印。

我正在尝试使用 memcpy 函数将输入的数组复制到链表中的数组。每当我在将数组复制到链表后尝试将数组打印回来时,它都无法正确打印。 share 和 price 数组的前三个条目打印正确,但第四个 share 条目打印一个巨大的数字,而第四个 float 条目打印为零。

感谢您的帮助。

【问题讨论】:

  • scanf("%s", &amp;tic); ...scanf("%s", &amp;nam) 你在这里不需要&amp;

标签: c arrays linked-list


【解决方案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 使用正确的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多