我正在编写一个“纳米社交网络”,只需注册一个成员并使用结构中的指针连接它们。我正在尝试使用一个连接函数,其中我不确定我是以正确的方式编写它,因为当我尝试运行它时程序崩溃并且我得到0个错误和0个警告(使用CodeBlocks在高级警告)。
首先我注册了至少2个成员然后当我尝试通过connect()函数连接它们时,我得到了我想要连接的用户不存在,这是函数中条件的一部分。我正在注册的用户是不是被保存在内存中?或者我写错了什么?
连接功能可以通过各种方式简化,但是一旦我清楚自己的错误,我就会这样做。
代码:
#include <stdio.h>
#include <stdlib.h>
struct member{
int num;
char name[10];
struct member *m1;
struct member *m2;
struct member *m3;
struct member *m4;
struct member *m5;
}*ptr[5];
void addmember(){
int i;
printf("Enter new members details:\n");
for(i=0; i<4; i++){
ptr[i] = malloc(sizeof(struct member));
printf("\n Enter ID number:\n");
scanf("%d", &ptr[i]->num);
printf("\n Enter Name:\n");
scanf("%s", ptr[i]->name);
}
printf("\n Added member details are:");
for(i=0; i<4; i++){
printf("\n ID number : %d", ptr[i]->num);
printf("\nName : %s", ptr[i]->name);
}
}
void connect(){ //when always typing the first username
int i=0;
printf("Please type in your user name : \n");
scanf("%s", ptr[i]->name);
if(ptr[i]->name == ptr[0]->name){ //being first user connecting.
printf("Please type existing member name you wish to connect with :\n");
scanf("%s", ptr[i]->name);
if(ptr[i]->name == ptr[1]->name){
ptr[0]->m1 = ptr[1]->m1;
ptr[1]->m2 = ptr[0]->m2;
printf("member 1 connected with member 2!\n");
}
else if(ptr[i]->name == ptr[2]->name){
ptr[0]->m1 = ptr[2]->m1;
ptr[2]->m3 = ptr[0]->m3;
printf("member 1 connected with member 3!\n");
}
else if(ptr[i]->name == ptr[3]->name){
ptr[0]->m1 = ptr[3]->m1;
ptr[3]->m4 = ptr[0]->m4;
printf("member 1 connected with member 4!\n");
}
else if(ptr[i]->name == ptr[4]->name){
ptr[0]->m1 = ptr[4]->m1;
ptr[4]->m5 = ptr[0]->m5;
printf("member 1 connected with member 5!\n");
}
else{
printf("User you typed in does not exist\n");
}
}
}
int main(){
int op = 0;
printf("Welcome to NSN, please register 4 members to proceed to options menu.\n");
addmember(); //adding 4 members
//general member section
printf("Now please select an option by typing option number\n");
while(op != 3){
printf("\n");
printf("1. Add new member.\n 2. Connect with member.\n 3. Exit\n");
printf("Enter your choice:\n");
scanf("%d", &op);
switch(op){
case 1:
addmember();
break;
case 2:
connect();
break;
case 3:
printf("Bye!\n");
exit(0);
break;
default:
printf("Invalid choice!\n");
}
}
return(0);
}
如前所述,当我在注册至少3名成员并输入现有名称后使用连接功能时,我总是得到答案“你输入的用户不存在”,这是某种方式,我不是在保存这个记忆还是我错过了一个功能?
答案 0 :(得分:2)
你无法比较像这样的scope_master
数组,你要比较这些指针指向的地址:
char
您必须使用strcmp
功能:
ptr[i]->name == ptr[0]->name
另外,请考虑一下您的strcmp(ptr[i]->name, ptr[0]->name)
功能 - 为什么使用第一个connect
输入 - member
?您更愿意输入成员 A 和 B 的名称,在scanf("%s", ptr[i]->name);
数组中找到他们的位置,然后连接它们。
我也不明白为什么你在ptr
本身有member
的这五个指针。你已经有了一个数组。