【问题标题】:Error in memory allocation of a struct field结构字段的内存分配错误
【发布时间】:2021-08-06 17:04:20
【问题描述】:

附上最小示例:

struct MyStruct {
    int a;
};

void testFun(struct MyStruct* testStruct) {
    printf("a: %s", testStruct->a);
}; 

void main(){
    struct MyStruct testStruct = { .a = 1 };
    testFun(&testStruct);
};

这让我很震惊:test.exe 中的 0x791428BC (ucrtbased.dll) 抛出异常:0xC0000005:访问冲突读取位置 0x00000001。

我在这里缺少什么?

【问题讨论】:

  • 你用的是什么编译器?不是告诉你格式字符串和参数不匹配吗?

标签: c struct memory-management


【解决方案1】:

试试下面的代码:

#include <stdio.h>

struct MyStruct {
    int a;
};

void testFun(struct MyStruct* testStruct) {
    printf("a: %d\n\n", testStruct->a);
}; 

int main(){
    struct MyStruct testStruct = { .a = 1 };
    testFun(&testStruct);
    return(0);
};

输出应类似于以下文本:

a: 1

【讨论】:

【解决方案2】:

%s 用于打印字符串(以空字符结尾的字符序列),它需要一个指针 char* 指向字符串的第一个元素。

您应该使用%d 以十进制打印int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-21
    • 2021-06-12
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    相关资源
    最近更新 更多