I'd suggest that you make ptr_friends
a pointer to multiple chars by using malloc(size_t)
and then resizing the space with realloc(void *, size_t)
everytime you want to add an ID to the friendlist. That way you can just get the numbers using ptr_friends[i]
.
For example :
int friends_size = 1;
char *ptr_friends = malloc((size_t)1);
ptr_friends[0] = john_id; // john_id is a fictional ID here
And when you want to add a friend :
ptr_friends = realloc(ptr_friends, ++friends_size);
ptr_friends[friends_size-1] = mary_id;
EDIT :
If you want to make a function to add a friend, for example addfriend(char *,int)
, doing the following is an error :
void addfriend(char *ptr_friends, int *friends_size, int id)
{
ptr_friends = realloc(ptr_friends, (size_t) ++(*friends_size));
ptr_friends[friends_size-1] = id;
}
ptr_friends
here is getting reallocated, and since the pointer can move while being reallocated, we're storing it in ptr_friends
. But, it's the ptr_friends
from inside the function, that means that the pointer we give to the function will not get modified, since arguments to a function are copied elsewhere beforehand. That means that you have to give a pointer to the pointer, so you can modify the pointer in the main code.