adding a new user to list in c program -
im trying write simple function addd friend useraccount list. information provided through parameter. if user in list not need add him again display records saying in list. wrote piece of code. not sure if correct, suggestion improve code? work?
int add_friend(useraccount* user, char circle, useraccount* friend) { struct useraccountnode *p; p = (struct useraccountnode *) malloc(sizeof(struct useraccountnode)); while (p != null) if(stricmp(user, p->friend) == 0){ p->next = head; // inserting @ beginning head = p; } else { printf("%d exists", friend) }; }
"not sure if correct" - intended do? if so, might correct; if not. well...
and no, near correct. list of things wrong make decent case scrapping all of it. such things include (but not limited to):
you claim want conditionally add new friend if they're not in list. yet first thing allocate space you're not sure need yet?
your loop has no exit condition can possibly met (unless
malloc()fails). @ no timep, exit condition argument, ever assigned anything after first line in function, assigns dynamic allocation may not need. i.e. have infinite loop.you're passing
useraccount*stricmpfirst parameter, expectsconst char*.you're comparing
p->frienduser. you allocatedppoints to.friendmember indeterminate, i.e. has no defined content, yet you're sending undefined contentstricmp()compare against input parameteruser. invokes undefined behavior.the comparison logic backwards.
stricmp()returns 0 if strings case-insensitive equal; not different. logic (even if weren't invoking undefined behavior due prior item mentioned above) @ least attempting add items list if they're present.after 2 iterations through list, if miracle if-expression evaluated true twice, have created circular self-referencing node , orphaned list had abyss.
you're sending
friend,useraccount*,printf"%d"format specifier. while likely won't crash program, none-the-less more undefined behavior. if want print pointer valueprintf()use"%p"the unused function parameters least of worries. may not have been used, on plus side, likewise weren't used incorrectly; cannot said
user,friend.
i'm not going shine on "good effort" or "nice try". there no chance code compiled, , absolutely zero chance ever run correctly. need review actual algorithm you're trying implement, , heavily review usage of pointers , dynamic memory in c.
Comments
Post a Comment