mike
mike

Reputation: 787

C - unsigned char in a struct

Can someone please explain to me the reason I get different results in the output?

I have defined a list using list nodes:

typedef struct list_node
    {
        unsigned char letter;
        struct list_node *next;
    } ListNode;

typedef struct list
    {
        ListNode *head; 
    } List;

and these functions for a newlist, and for getData:

List* newList(unsigned char a) {
    List* new_list = (List*)malloc(sizeof(List));
    ListNode s1 = { a, NULL };
    ListNode* s2 = &s1;
    new_list->head = s2;

    return new_list;
}

unsigned char getData(List *list){
    ListNode *tmp = list->head;
    ListNode d = *tmp;

    return d.letter;
}

but, when I try to test it and print the unsigned char with my getData function, I get a strange result:

unsigned char b = 'b';
List* check = newList(b);
unsigned char lettercheck = getData(check);
printf("%u\n",lettercheck);

This prints out the value 204, but when I use printf("%u\n", b); it prints 98, as it should of course.

I even tried defining the listnode itself like this:

List* check = newList(b);
ListNode* d = check->head;
ListNode e = *d;
printf("%u\n", e.letter );

which basically just mimics what my function does, and then it prints 98.

Can somebody please explain this to me? I've been puzzled for quite some time.

Upvotes: 0

Views: 1777

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

Because

ListNode s1 = { a, NULL };

is a local variable, it exists within the stack frame of the newList() function, and when the function returns it no longer exists, but yet you have a pointer to it in your struct.

Try this

ListNode *s1 = malloc(sizeof(ListNode));
if (s1 == NULL)
    handleThisErrorAndDoNotContinuePlease();
s1->letter = a;
s1->next   = NULL;

new_list->head = s1;

Some tips:

  1. Check for malloc return value against NULL
  2. Don't cast the result of malloc it's not needed.
  3. Don't forget to call free() whenever you finish using the malloced pointers.

Upvotes: 2

Related Questions