I'm currently self-studying C for mastering an university project. In that project we have several signatures given that we need to implement for solving our task. After several hours of trying to make some progress, I must admit that I'm totally confused about the return types of functions. I will show you some code:
This is a structure given to represent numbers in the power to the basis 32.
#include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint32;
typedef struct
{
int n;
uint32* words;
}
foo;
We need to implement some functions like the one with the following signature:
foo add(foo* a, foo* b);
As can you see, the function takes two pointers to the structure as parameters, and returns the value of a structure, and not the pointer to it. That means that I have to locally create an instance of foo and return it.
foo add(foo* a, foo* b)
{
foo result = {1, malloc(sizeof(uint32))};
// do something with result
return result;
}
1) Is there anything wrong in this attempt? In my production code I get problems with accessing the value of the returned structure: it seems to they have changed after the structure was returned. Unfortunately I was not able to reproduce that behaviour in a more simple application, which got me even more worried that I'm doing this all wrong. I have also tried to allocate memory with malloc for the variable result, but that only seems to work if I create a pointer to foo, which seems to be no option, because I can't return the pointer.
2) I'm looking for a way to cast (probably not the correct term) the return type back into a pointer. Lets just say I have this code:
foo* bar1 = malloc(sizeof(foo));
bar1->n = 1;
bar1->words = malloc(bar1->n * sizeof(uint32));
bar1->words[0] = 4294967295;
foo* bar2 = malloc(sizeof(foo));
bar2->n = 1;
bar2->words = malloc(bar2->n * sizeof(uint32));
bar2->words[0] = 21;
foo bar3 = add(bar1, bar2);
Works fine. How could I now use the value of bar3 to call the add function again. Like this:
foo bar4 = add(bar1, bar3);
After also tried various attempts with creating foo* and trying to assign values, but they all failed and I decided to post this question to get some nice answer that helps me understanding C a little bit more.
Thanks for everybody who tries to help, I appreciate that ;)