c - 创建链表时遇到问题

标签 c arrays linked-list

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

#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 函数将输入的数组复制到链表中的数组。每当我在将数组复制到链接列表后尝试将其打印出来时,它都无法正确打印。股票和价格数组的前三个条目打印正确,但第四个股票条目打印出一个巨大的数字,第四个 float 条目打印为零。

感谢您的帮助。

最佳答案

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) 可以保证为 使用正确的类型大小

关于c - 创建链表时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48939809/

相关文章:

php - 没有回调的 array_filter 有什么作用?

java - 为什么链表更快

python - 具有哈希表空间的循环双向链表

c - 从 linux 内核或 udev 监听硬件变化事件

将char数组的一部分复制到c中的字符串

c - C 中的蜂窝自动化存在问题

arrays - 给定一个未排序的数组,求数组中两个元素之间的最大减法

c++ - 链表中的链表 - 节点无法初始化

javascript - 发送数据的时间计数器

c - 静态常量存储在哪里?