我使用结构和指针制作了一个简单的 friend 列表,但我的代码有一些问题'它没有打印正确的内容
typedef struct friends {
int namesize;
char* myfriends;
}friends;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void)
{
int numfriends = 0;
int*p_friends = &numfriends;
int i = 0, count = 0;
printf("Welcome , here is a list of your friends \n");
printf("plesase enter the number of your friends \n");
scanf("%d", &numfriends); //gets the number of the friends
printf("you have %d friends \n", numfriends);
friends *f= malloc(sizeof(friends) * numfriends); // malloc
printf("now please enter thier'S name \n");
for (i = 0; i < numfriends; i++)
{
count++; // for looking at the number of the friend
(f+i)->myfriends= (char*)malloc(sizeof(char) * numfriends); // malloc
printf("enter the name of friend NO.%d ", count);
fgets((f + i)->myfriends,20,stdin); // entering the names of the friends
(f +i)-> namesize = strlen((f + i)->myfriends) + 1;
((f + i)->myfriends) = (char*)realloc((f + i)->myfriends, sizeof(char) * numfriends * (f + i)->namesize); //realloc
}
for (int j = 0; j < numfriends; j++)
{
printf("The name of friend NO %d is: %s \n", j + 1, ((f + j)->myfriends)); //printing the names
free((f + j)->myfriends);
}
system("pause");
return 0;
}
当我尝试打印 friend 列表时:
我该如何解决这个问题?
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct friends {
int namesize;
char* myfriends;
}friends;
#define MAX_NAME_SIZE 20
int main(void){
int numfriends = 0;
//int*p_friends = &numfriends;//unused
int i = 0, count = 0;
printf("Welcome , here is a list of your friends \n");
printf("plesase enter the number of your friends \n");
scanf("%d%*c", &numfriends); //%*c eat newline
printf("you have %d friends \n", numfriends);
friends *f= malloc(sizeof(friends) * numfriends);
printf("now please enter thier'S name \n");
for (i = 0; i < numfriends; i++){
count++; // for looking at the number of the friend
f[i].myfriends = (char*)malloc(sizeof(char) * (MAX_NAME_SIZE + 1));//f[i]. short than (f+i)->
printf("enter the name of friend NO.%d ", count);
fgets(f[i].myfriends, MAX_NAME_SIZE + 1, stdin); // entering the names of the friends
f[i].myfriends[strcspn(f[i].myfriends, "\n")] = '\0'; //remove newline
f[i].namesize = strlen(f[i].myfriends) + 1;
f[i].myfriends = realloc(f[i].myfriends, f[i].namesize);//Cast is not necessary in C. alos sizeof(char) is always 1 in C.
}
for (int j = 0; j < numfriends; j++){
printf("The name of friend NO %d is: %s \n", j + 1, f[j].myfriends); //printing the names
free(f[j].myfriends);
}
free(f);
system("pause");
return 0;
}
关于c - 具有结构体和指针的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36536428/