美文网首页
14.6 结构和其他数据形式:结构、指针、malloc()

14.6 结构和其他数据形式:结构、指针、malloc()

作者: 日常表白结衣 | 来源:发表于2017-07-22 19:41 被阅读0次

在结构中使用字符数组来存储字符串,但是使用指向char的指针来代替字符数组会更加方便。

struct pnames{
  char * first;
  char *last;
}

但是此处没有初始化指针,此时的变量地址可能是任何值,所以是不安全的。
但是如果使用malloc()函数来分配内存并使用指针存储该地址,那么在结构中使用指针处理字符串就比较合理。
【关于malloc()函数】

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char *p;

    p = (char *)malloc(100); //分配内存
    if (p)
        printf("Memory Allocated at: %x", p);
    else
        printf("Not Enough Memory!");
    free(p); //释放内存

    return 0;
}

【改写14.5程序示例】

#include<stdio.h>
#include<string.h> //提供strcpy()函数、strlen()函数
#include<stdlib.h> //提供malloc()函数、free()函数
#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);
    //分配内存
    pst->fname = (char *)malloc(strlen(temp) + 1);
    //数组拷贝
    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;
}

相关文章

网友评论

      本文标题:14.6 结构和其他数据形式:结构、指针、malloc()

      本文链接:https://www.haomeiwen.com/subject/pvuukxtx.html