【C 语言】数组 ( 指针数组用法 | 菜单选择 )
生活随笔
收集整理的這篇文章主要介紹了
【C 语言】数组 ( 指针数组用法 | 菜单选择 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、指針數組用法 ( 菜單選擇 )
- 二、完整代碼示例
一、指針數組用法 ( 菜單選擇 )
使用場景 : 用戶輸入一個 字符串 , 判定該 字符串 是菜單中的哪個選項 ;
定義 指針數組 , 數組中存放著指針 , 每個指針指向 字符串 常量 , 字符串常量在 全局區 中的 常量區 ;
// 指針數組 , 數組中存放著指針 , 每個指針指向 字符串 常量// 字符串常量在 全局區 中char *menu_array[] = {"query","update","insert","delete"};將 指針數組 菜單 和 指針數組 大小 , 以及要查詢的 字符串 ;.
- 計算數組大小 : 使用如下宏定義 , 計算數組大小 ;
- 函數參數定義 :
遍歷 指針數組 , 查找字符串位置 :
// 遍歷字符串數組for(i=0; i < array_size; i++){// 如果找到字符串 , 則返回if(strcmp(str, menu_table[i]) == 0){*menu_position = i;return ret;}}二、完整代碼示例
完整代碼示例 :
#include <stdio.h> #include <stdlib.h> #include <string.h>// 計算數組長度 #define LEN(array) (sizeof(array) / sizeof(*array))/*** @brief searche_menu_table 菜單列表 中查找 字符串位置* @param menu_table 指針數組 , 數組元素是指針 , 指針指向字符串* @param array_size 指針數組 中 元素個數* @param str 要查找的字符串* @param menu_position 字符串位置* @return 返回函數是否執行成功*/ int searche_menu_table(const char *menu_table[], const int array_size, const char* str, int *menu_position) {// 函數返回值, 標志函數執行結果狀態 , 0 表示執行成功int ret = 0;// 循環控制變量int i = 0;// 驗證指針合法性if (menu_table==NULL || str==NULL || menu_position==NULL){ret = -1;printf("error : menu_table==NULL || str==NULL || menu_position==NULL");return ret;}// 遍歷字符串數組for(i=0; i < array_size; i++){// 如果找到字符串 , 則返回if(strcmp(str, menu_table[i]) == 0){*menu_position = i;return ret;}}// 在 menu_table 字符串數組中 , 沒有找到 str 字符串// 返回 -2 錯誤狀態ret = -2;// 設置 -1 位置*menu_position = -1;return ret; }/*** @brief 主函數入口* @return*/ int main() {// 記錄字符串在菜單中的位置int menu_position = 0;int i = 0;// 指針數組 , 數組中存放著指針 , 每個指針指向 字符串 常量// 字符串常量在 全局區 中char *menu_array[] = {"query","update","insert","delete"};// 在 字符串指針數組 中 查詢對應字符串searche_menu_table( menu_array, LEN(menu_array),"delete", &menu_position);// 打印查找到的位置printf("menu_position = %d\n", menu_position);// 命令行不要退出system("pause");return 0; }執行結果 :
menu_position = 3 請按任意鍵繼續. . . 《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的【C 语言】数组 ( 指针数组用法 | 菜单选择 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【C 语言】数组 ( 指针退化验证 |
- 下一篇: 【C 语言】数组 ( 指针数组用法 |