- Note: If you want to use a structure to store a string, using a character array as a member is relatively simple. A pointer to
char also works, but misuse can lead to serious problems. (So, to be safe, just use a character array)
There Is a Problem with the Code in Section 14.7.7; the Code Is as Follows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SLEN 81
struct namect {
char* fname;
char* lname;
int letters;
};
void getinfo(struct namect*);
void makeinfo(struct namect*);
void showinfo(const struct namect*);
void cleanup(struct namect*);
char* s_gets(char* st, int n);
int main(void)
{
struct namect person;
getinfo(&person);
makeinfo(&person);
showinfo(&person);
cleanup(&person);
return 0;
}
void getinfo(struct namect* pst)
{
char temp[SLEN];
printf("Please enter your first name.\n");
s_gets(temp, SLEN);
// 分配内存以存储名
pst->fname = (char*)malloc(strlen(temp) + 1);
// 把 first name 拷贝到动态分配的内存中
if (pst->fname != NULL)
strcpy_s(pst->fname, sizeof(pst->fname), temp);
printf("Please enter your last name.\n");
s_gets(temp, SLEN);
pst->lname = (char*)malloc(strlen(temp) + 1);
if (pst->lname != NULL)
strcpy_s(pst->lname, sizeof(pst->lname), temp);
}
void makeinfo(struct namect* pst)
{
pst->letters = strlen(pst->fname) + strlen(pst->lname);
}
void showinfo(const struct namect* pst)
{
printf("%s %s, your name contains %d letters.\n", pst->fname, pst->lname,
pst->letters);
}
void cleanup(struct namect* pst)
{
free(pst->fname);
free(pst->lname);
}
char* s_gets(char* st, int n)
{
char* ret_val; // 该指针用于保存读取的字符串的字符首地址
char* find; // 用于保存从字符串中找到的换行符'\n'的地址
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}

- 2022.1.5 (Leaving this unresolved for now; I cannot solve the problem at present and will come back to it later)
typedef
- In a
typedef definition, uppercase letters are typically used for the name being defined to remind the user that this type is actually a symbolic abbreviation.
Functions and Pointers
- If you want to declare a pointer to a function of a certain type, you can write the function's prototype and then replace the function name with an expression in the form (*pf). Then
pf becomes a pointer to a function of that type.