c - 结构不返回正确的值

标签 c struct return

当我在 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/

相关文章:

c++ - 在方法中返回静态变量是个坏主意吗?

c - 正确分配多维数组

C - 交换双向链表中的第一个和最后一个元素

c - 了解结构体和 malloc 中的指针

java - 如果不返回值,为什么要使用 return 关键字?

go - 在 Go 中用递归练习 "Naked Returns"。我的ELSE语句中的return语句不正确吗?

C 链表冒泡排序逻辑错误

c - 处理非常小的堆栈有什么技巧吗?

c - 隐藏结构成员

c - 结构指针中需要一些说明