I have defined a structure for users as USER:
struct user {
char *name;
int age;
};
typedef struct user USER;
And I can create an array of users:
USER uArray[3] = {
{ "Allan", 12 },
{ "Bob", 34 },
{ "Chris", 56 }
};
Now how do I go about adding a predefined user to a list of users?:
USER u1 = { "Dave", 78 };
I assumed that you could just add it to the list as followed. However, an error is returned, stating that it cannot convert from 'USER' to 'char*'.
USER uArray[4] = {
{ "Allan", 12 },
{ "Bob", 34 },
{ "Chris", 56 },
u1
};
I understand that its treating u1 as the first element of creating a user (name = u1) so how else can you add a predefined user to an array of users?
The code is now working:
#include <stdio.h>
struct user {
char *name;
int age;
};
typedef struct user USER;
void changeName(USER *u);
void main(void)
{
USER u1 = { "Dave", 78 };
USER uArray[4] = {
{ "Allan", 12 },
{ "Bob", 34 },
{ "Chris", 56 }
};
// add u1 to position 3 of the array
uArray[3] = u1;
for (int i = 0; i < 4; i++)
{
if (uArray[i].name == "Bob")
{
changeName(&uArray[i]);
}
printf("User: %d, Name: %s, Age: %d\n", i, uArray[i].name, uArray[i].age);
}
}
void changeName(USER *u)
{
u->name = "Dave";
}
u1in your code? That would at least explain the error about converting fromUSERtochar. The stack corruption happens probably elsewhere, so you should post more code. (If the program is large, try to isolate the error in a few lines and post only these.)