1

I need to create mini social network in C. I made a struct for each person. And I'm storing each friend in a char pointer with id's. I thought I can manage it like this:

ptr_friends = id1,id2,id3,id4...

and when I need them I could just read those by using strtok.

But I couldn't manage to save it that way. It should be like this:

ptr_friends = ptr_friends + id + ","

but of course it doesn't work this why and I don't know how to do it.

How can I save and use this way? Or if you have another idea for a save method please tell.

Sebastian
  • 8,046
  • 2
  • 34
  • 58
bassmove
  • 11
  • 1

4 Answers4

1

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.

Josselin Poiret
  • 508
  • 3
  • 10
0

I guess this will help you : https://stackoverflow.com/a/5901241/2549281

You should use something like :

strcat(ptr_friends, id);
strcat(ptr_friends, ",");

instead of ptr_friends + id + ","

Community
  • 1
  • 1
Dabo
  • 2,371
  • 2
  • 18
  • 26
0

Would not it be easier to you to do an array of ints with ids?

int max_friends  = 50;
int friends_size = 0;
int friends*     = malloc(sizeof(int) * MAX_FRIENDS);
friends[friens_size] = id;
friends_size++;
MiguelAngel_LV
  • 1,200
  • 5
  • 16
0

Another suggestion is instead of using a string or a simple array you can use a "generic" dynamic array (using void*). It's a simple code and you can find many examples.

take a look at that question: C dynamically growing array

Community
  • 1
  • 1
AndreDurao
  • 5,600
  • 7
  • 41
  • 61