I am trying to get a better understanding of how one would structure an API in C.
- I create a struct
Person - I have a
initfunction that sets data on that struct - I have multiple "helper" functions that work on that struct
I'm wondering if the following code in C can be considered idiomatic from the point of view of more seasoned C developers.
#include <stdio.h>
#include <stdlib.h>
typedef struct Person Person;
struct Person
{
unsigned int age;
unsigned int weight;
Person *next_person;
};
void person_init(Person *p, unsigned int age, unsigned int weight, Person *next_person)
{
p->age = age;
p->weight = weight;
p->next_person = next_person;
}
void person_print(Person *p)
{
printf("person is %dy old\n", p->age);
printf("person weight is %dkg\n", p->weight);
}
int main(void)
{
Person p1, p2, p3, p4;
Person *p_cur;
person_init(&p1, 28, 80, &p2);
person_print(&p1);
person_init(&p2, 58, 93, &p3);
person_print(&p2);
person_init(&p3, 60, 60, &p4);
person_print(&p3);
person_init(&p4, 78, 50, NULL);
person_print(&p4);
printf("==================\n");
p_cur = &p1;
while (p_cur != NULL) {
person_print(p_cur);
p_cur = p_cur->next_person;
}
return 0;
}
In particular I'm unsure about the signature of the functions in general and about the use of a Person * pointer.
When is it OK to not-pass a pointer but the struct/char array directly?
In most APIs I have seen so far, a pointer to the struct/char array is passed, like snprintf(char * s, ... ). But sometimes, like in getline(char **lineptr, ...) even a char ** is passed. Why? When make the distinction?
char *pretty much means "String" in old-style C, because there is no built-inStringtype. Readchar **asString *and things look much more consistent.char *just as well?charstring with'\0'.