【发布时间】:2023-01-19 21:51:17
【问题描述】:
如果第一个目的地输入 1,日期输入 2,第二个目的地输入 3,日期输入 4,最后一个目的地输入 5,日期输入 6,则结果均显示为 5 和 6。
我很感激你的帮助。
我想知道输出值都是5和6。 (你必须在结构内部写一个指针。)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#pragma warning(disable:4996)
void fillFlightInfo(struct FlightInfo* db, char* destinationStr, char* dateStr);
void printFlightInfo(struct FlightInfo* db);
void clearCR(char* buf);
struct FlightInfo
{
char* destination;
char* date;
};
int main(void)
{
struct FlightInfo* pData = NULL;
char destinationStr[30] = "";
char dateStr[30] = "";
pData = (struct FlightInfo*)malloc(4 * sizeof(struct FlightInfo));
struct FlightInfo* db = pData; //the beginning address
if (pData == NULL)
{
printf("Out of memory\n");
return -1;
}
for (int i = 1; i < 4; i++)
{
fillFlightInfo(db + i, destinationStr, dateStr); // (db + i)
printf("%d %35s %35s\n", i, (db + i)->destination, (db+i)->date);
db++;
}
printf("\n");
db = pData;
printFlightInfo(db);
if (pData != NULL)
{
free(pData);
}
return 0;
}
void fillFlightInfo(struct FlightInfo* db, char* destinationStr, char* dateStr)
{
printf("Enter a flight destination: ");
fgets(destinationStr, sizeof destinationStr, stdin);
db->destination = destinationStr;
clearCR(db->destination);
printf("Enter a flight date: ");
fgets(dateStr, sizeof dateStr, stdin);
db->date = dateStr;
clearCR(db->date);
}
void printFlightInfo(struct FlightInfo* db)
{
for (int i = 1; i < 4; i++)
{
printf("%d %35s %35s\n", i, (db + i)->destination, (db + i)->date);
db++;
}
}
void clearCR(char* buf)
{
char* whereCR = strchr(buf, '\n');
if (whereCR != NULL)
{
*whereCR = '\0';
}
}
/*
*** input ***
1
2
3
4
5
6
*** output ***
1 5 6
2 5 6
3 5 6
*/
【问题讨论】:
-
首先决定你使用哪种语言编程。C 和 C++ 是两种语言非常不同的语言,使用 C++,您的代码应该看起来非常不同的。
-
至于你的问题,你有一“目的地”字符串,和一“日期”字符串,并且您使所有指针都指向这些单个字符串。也可以考虑在结构中使用数组,并改为复制字符串。
-
问自己一个非常简单的问题:您正在读取多条记录,您正在为每条记录使用完全相同的缓冲区集,您如何期望最终得到不同的记录,这些记录被读入完全相同的缓冲区集?一旦你弄清楚了这个问题的答案,一切就会迎刃而解。
-
另一方面,
(db + i)->destination是确切地与db[i].destination相同。后者(使用数组索引)更容易阅读、理解、维护,也更容易编写。 -
所有 3 个结构中的所有指针最终都指向局部函数变量
char destinationStr[30]和char dateStr[30]的相同内存地址。您使用 fgets 将某些内容读入这些字符数组。然后将指针复制到第一个结构变量,然后再次读入同一内存并将指针复制到第二个结构。因为第一个结构仍然指向相同的内存,所以它们都具有相同的“值”。读入缓冲区后,您需要为每个结构的char*分配内存并从缓冲区复制到它以保存数据。
标签: c