Gideon Kogan
Gideon Kogan

Reputation: 763

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.

What I am missing here?

Upvotes: 0

Views: 61

Answers (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

Upvotes: -2

MikeCAT
MikeCAT

Reputation: 75062

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

Upvotes: 4

Related Questions