14.6 结构和其他数据形式:结构、指针、malloc()
来源:互联网 发布:虚拟机安装nginx 编辑:程序博客网 时间:2024/05/29 11:38
在结构中使用字符数组来存储字符串,但是使用指向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 81struct 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;}
阅读全文
0 0
- 14.6 结构和其他数据形式:结构、指针、malloc()
- 14.5 结构和其他数据形式:指针和结构
- 结构和其他数据形式
- C -- 结构和其他数据形式
- 第十四章 结构和其他数据形式
- C语言结构和其他数据形式
- C 结构和其他数据形式
- 14.1 结构和其他数据形式:结构体
- 14.2 结构和其他数据形式:嵌套结构
- 14.5 结构和其他数据形式:传递结构
- C学习笔记(九)结构和其他数据形式
- C的结构体和其他数据形式
- C语言再学习 -- 结构和其他数据形式
- C primer plus第14章(结构和其他数据形式)
- C primer plus第14章(结构和其他数据形式)(练习)
- c primer plus第14章总结:结构和其他数据形式
- 14 章 结构和其它数据形式
- 结构体和指针
- 14.5 结构和其他数据形式:指针和结构
- 微信小程序(5)-新闻页面制作(1)
- 14.5 结构和其他数据形式:传递结构
- Objective-C NSValue详解
- Android6.0运行时权限
- 14.6 结构和其他数据形式:结构、指针、malloc()
- Apk打包与多渠道打包
- 自己写的一个打log的工具类,没啥技术含量,可以直接粘走用
- 了解Gtest中的事件机制
- 14.18.4 嵌套结构数组
- 16.3.1 用宏参数创建字符串
- cordova build app时候 提示没有gradle android studio
- Flex布局布局
- 16.3.1 预处理粘合剂:##运算符