简体   繁体   English

结构字段的 memory 分配错误

[英]Error in memory allocation of a struct field

Attached minimal example:附上最小的例子:

struct MyStruct {
    int a;
};

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

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

which throughs me out with: Exception thrown at 0x791428BC (ucrtbased.dll) in test.exe: 0xC0000005: Access violation reading location 0x00000001.这让我明白: test.exe 中的 0x791428BC (ucrtbased.dll) 抛出异常:0xC0000005:访问冲突读取位置 0x00000001。

What I am missing here?我在这里缺少什么?

%s is for printing strings (sequences of characters terminated by a null-character) and it expects a pointer char* to the first element of the string. %s用于打印字符串(由空字符终止的字符序列),它需要一个指针char*指向字符串的第一个元素。

You should use %d to print an int in decimal.您应该使用%d以十进制打印int

Try the code below:试试下面的代码:

#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);
};

Output should look like the following text: Output 应类似于以下文本:

a: 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM