Reputation:
My goal is to create an fisrt
of my custom struct
type.
When run, prints out 24.
Can't understand why:
#include <stdio.h>
typedef struct strktura {
int number;
char name;
} strktura;
strktura new_one(int number, char name){
strktura a;
a.number=number;
a.name=name;
}
main()
{
strktura first=new_one(2,"A");
printf("%d\n",first.number);
}
Upvotes: 0
Views: 48
Reputation: 399
You need to add a
return a;
in your new_one() function so that the structure gets returned from the function new_one()
Upvotes: 0
Reputation: 134336
You forgot to return
from new_one()
.
Related Reading: From chapter 6.9.1, paragraph 12, C11
document,
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
So, in your code, without a return
from new_one()
and by accessing the return value through printf("%d\n",first.number);
, you're facing undefined behaviour.
Also, worthy to mention, the correct syntax for main()
is int main()
, (and a matching return 0
is a good practice.)
Upvotes: 4