Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which convention is better in C programming?

Tags:

c

pointers

struct

My question refers to the topic of C pointers. Imagine the following scenario: I have a struct variable named "stc" defined like this:

struct stc {
       int data;
       char ch;
}

declared in the beginning of the Main() function in my program. I would like to set the values the fields in the struct (i.e. data) using a function.

Now my question is which of the following convention is better and why?

Convention 1: Write a function the return a pointer of type stc:

struct stc *func(int d, char c)
{
    stc *tmp = malloc(sizeof(stc))
    tmp -> data = d;
    tmp -> ch = c;

    return tmp;
}

and later on free the allocated memory when the structure is no longer needed.

Convention 2: Write a function that receives a pointer to the struct and send it the address of stc

void func(stc *stcP, int d, char c)
{
     stcP -> data = d;
     stcP -> ch = c;
}

Thanks a lot!

like image 386
omer Avatar asked Dec 20 '22 00:12

omer


1 Answers

The first usage could cause memory leak without care.

The second usage is better, but you use the arrow operator incorrectly, it should be:

void func(stc *stcP, int d, char c)
{
    stcP -> data = d;
    stcP -> ch = c;
}
like image 102
Yu Hao Avatar answered Jan 03 '23 21:01

Yu Hao