How to correctly allocate memory for a structure in a function in order to return its value for later use and how to convert the structure to a pointer?

I am currently learning C on my own to master a university project. In this project, we have several signatures that we need to implement to solve our problem. After hours of trying to make some progress, I have to admit that I'm completely confused by the return types of functions. I will show you the code:

This is a structure designed to represent power numbers on a basis of 32.

#include <stdio.h>
#include <stdlib.h>

typedef unsigned int uint32;
typedef struct 
{
  int n;
  uint32* words;
}
foo;

We need to implement some functions, for example, with the following signature:

foo add(foo* a, foo* b);

, , . , foo .

foo add(foo* a, foo* b)
{
  foo result = {1, malloc(sizeof(uint32))};
  // do something with result
  return result;
}

1) - ? : , . , , , . malloc , , foo, , , , .

2) (, ) . , :

   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);

. bar3 . :

   foo bar4 = add(bar1, bar3);

foo * , , , , C .

+3
3

. . valgrind, . , , . , , free() words, .

, , .

foo:

foo* add (foo* a, foo* n) {
  foo result* = malloc(...);

  /* do some addition */

  return result;
}

free() foo, .

, , , add():

  • add().
  • foo result.
  • add() .
  • add() , , .
  • undefined, , , .

:

  • add().
  • , result.
  • add() result ( , ).
  • add() , result, - , .
  • , free(result), .

, ! , .

+1

1) , - :

 printf("[bar3] n %d words %d\n", bar3.n, *(bar3.words));

2) bar3 add. bar3, &:

   foo bar4 = add(bar1, &bar3);

foo bar3_p = &bar3;
foo bar4 = add(bar1, bar3_p);

, .

+4

You are looking for a carrier address, &. & foo3 will return a pointer to foo3.

+2
source

Source: https://habr.com/ru/post/1759798/


All Articles