gpt4 book ai didi

c - 结构不返回正确的值

转载 作者:太空宇宙 更新时间:2023-11-04 04:32:08 25 4
gpt4 key购买 nike

当我在 Debug模式下运行我的代码时,我可以看到正确的值来自:

createBooking("SOME NAME", 1, 2, 3, 4, 5, 6, 7);

被发送到我的结构。但是当我试图在我的结构中调用某些东西时,我看不到它的值(value)。 printf 只是打印 0 而不是它应该打印的 2。是不是我在 main() 中的 printf 丢失了什么?或者它可能是什么?我老师一直在看代码,也找不到问题。

主.c:

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

int main() {
struct Booking booking;
createBooking("SOME NAME", 1, 2, 3, 4, 5, 6, 7);
printf("%d", booking.pNumber);

getchar();
return 0;
}

函数.c:

#include "functions.h"

struct Booking createBooking(char *aName, int aPNumber, int aStartWeek, int aStopWeek,
int aCabNr, int aCabType, int aLiftcard, double aTotCost)
{
struct Booking booking = *(struct Booking*)malloc(sizeof(struct Booking));

strncpy(booking.name, aName, strlen(aName) + 1);
booking.pNumber = aPNumber;
booking.startWeek = aStartWeek;
booking.stopWeek = aStopWeek;
booking.cabNr = aCabType;
booking.cabType = aCabType;
booking.liftCard = aLiftcard;
booking.totCost = aTotCost;

return booking;
}

函数.h:

#ifndef functions_h
#define functions_h

#include <stdio.h>
#include <string.h>

typedef struct Booking {
char name[30];
int pNumber;
int startWeek;
int stopWeek;
int cabNr;
int cabType;
int liftCard;
double totCost;
} booking;

struct Booking createBooking(char *aName, int aPNumber, int aStartWeek, int aStopWeek,
int aCabNr, int aCabType, int aLiftcard, double aTotCost);
int bookBooking(struct Booking b);

#endif

最佳答案

所以你像这样声明结构:

struct Booking booking;

声明一个具有未定义值的结构 - 在大多数编译器中为 NULL/0比您调用分配并返回新结构的 createBooking。而你忽略了返回值:

createBooking("SOME NAME", 1, 2, 3, 4, 5, 6, 7);

比起 printf 未分配的结构:

printf("%d", booking.pNumber);  

当然它会返回 0 或一些意想不到的东西。你需要做的是:

struct Booking booking = createBooking("SOME NAME", 1, 2, 3, 4, 5, 6, 7);
printf("%d", booking.pNumber);

正如 M.M 在评论中正确注意到的那样,您不需要在函数内部进行动态分配,您需要做的就是:

struct Booking createBooking(char *aName, int aPNumber, int aStartWeek, int aStopWeek, int aCabNr, int aCabType, int aLiftcard, double aTotCost)
{
struct Booking booking;

strncpy(booking.name, aName, strlen(aName) + 1);
booking.pNumber = aPNumber;
booking.startWeek = aStartWeek;
booking.stopWeek = aStopWeek;
booking.cabNr = aCabType;
booking.cabType = aCabType;
booking.liftCard = aLiftcard;
booking.totCost = aTotCost;

return booking;
}

关于c - 结构不返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34885793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com