Error in memory allocation of a struct field

0

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.

What I am missing here?

c
struct
memory-management
asked on Stack Overflow May 17, 2021 by Gideon Kogan • edited May 17, 2021 by Gideon Kogan

2 Answers

4

%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.

You should use %d to print an int in decimal.

answered on Stack Overflow May 17, 2021 by MikeCAT
-2

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:

a: 1
answered on Stack Overflow May 17, 2021 by Siddhartha Shivshankar • edited May 24, 2021 by Dharman

User contributions licensed under CC BY-SA 3.0