在結(jié)構(gòu)中使用字符數(shù)組來存儲字符串,但是使用指向char的指針來代替字符數(shù)組會更加方便。
struct pnames{
char * first;
char *last;
}
但是此處沒有初始化指針,此時的變量地址可能是任何值,所以是不安全的。
但是如果使用malloc()函數(shù)來分配內(nèi)存并使用指針存儲該地址,那么在結(jié)構(gòu)中使用指針處理字符串就比較合理。
【關(guān)于malloc()函數(shù)】
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *p;
p = (char *)malloc(100); //分配內(nèi)存
if (p)
printf("Memory Allocated at: %x", p);
else
printf("Not Enough Memory!");
free(p); //釋放內(nèi)存
return 0;
}
【改寫14.5程序示例】
#include<stdio.h>
#include<string.h> //提供strcpy()函數(shù)、strlen()函數(shù)
#include<stdlib.h> //提供malloc()函數(shù)、free()函數(shù)
#define SLEN 81
struct namect {
char * fname; //使用指針
char * lname;
int letters;
};
void getinfo(struct namect *);
void makeinfo(struct namect *);
void cleanup(struct namect *);
void showinfo(const struct namect *);
char *s_gets(char *st, int n);
int main()
{
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);
//分配內(nèi)存
pst->fname = (char *)malloc(strlen(temp) + 1);
//數(shù)組拷貝
strcpy(pst->fname, temp);
printf("pleasr enter your last name:\n");
s_gets(temp, SLEN);
pst->lname = (char *)malloc(strlen(temp) + 1);
strcpy(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;
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;
}