抱歉标题含糊不清,我不太确定如何解释发生了什么。我正在尝试创建一个链表,链表的每个条目包含两个字符串,一个可以容纳四个条目的整数数组和一个可以容纳四个条目的 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 条目打印为零。
感谢您的帮助。
最佳答案
tic
和 nam
已经是指针所以改变
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/