c - 为什么运行程序会出错?

标签 c pointers

我有一个错误,我找不到解决它的方法。我得到这个错误

Exception thrown at 0x504A3E6C (ucrtbased.dll) in ConsoleApplication3.exe: 0xC0000005: Access violation reading location 0x0047617A. On line 11.

#include "Entities.h"
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

Expense* createExp(int nr_ap, float price, char* type) {
    Expense *e = malloc(sizeof(Expense));
    e->nr_ap = nr_ap;
    e->price = price;
    e->type = malloc(sizeof(char)*strlen(type) + 1);  #Here is the problem.
    strcpy(e->type, type);
    return e;
}

void destroy(Expense *e) {
    free(e->type);
    free(e);

}

int getAp(Expense *e) {
    return e->nr_ap;
}

float getPrice(Expense *e) {
    return e->price;
}

char* getType(Expense *e) {
    return e->type;
}

/*
Create a copy
*/

Expense *copyExp(Expense *e) {
    return createExp(e->nr_ap, e->price, e->type);
}

void testCreateExp() {
    Expense *e = createExp(10, 120, 'Gaz');
    assert(getAp(e) == 10);
    assert(getPrice(e) == 12);
    assert(getType(e) == "Gaz");
    destroy(e);

}

int main() {
    testCreateExp();
}

最佳答案

Expense *e = createExp(10, 120, 'Gaz'); 没有意义。单引号用于单个字符,而不是 C 字符串。

例如char initial = 'G'; char* name = "Gaz";

尝试 Expense *e = createExp(10, 120, "Gaz");。大多数编译器应该警告您在这种情况下使用单引号是不正确的。

还怀疑您的断言不是“预期的” assert(getType(e) == "Gaz"); - 不应该是 strcmp()

关于c - 为什么运行程序会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43036403/

相关文章:

c - 如何在C中的指针(**指针)的末尾添加一个字符串

c - 指向恒定大小的二维数组中的一维数组的指针

将字符串转换为 int(但前提是确实是 int)

c - 在具有重复值的未排序数组中查找缺失的数字

C 使用嵌套循环计算年降雨量总量,并匹配用户输入

c - Vugen - 将图像文件从一个文件夹复制到共享目录 - 仅限 C 代码

swift - 在 Swift 中将 UnsafeMutableBufferPointer<Bit> 转换为 NSData

c - 尝试从二叉搜索树中删除节点时获取 SEGFAULT

c - 获取指向二维数组的指针

c - 左移一个正整数给我一个负数