簡體   English   中英

結構數組和使用函數指針的變量

[英]Array of structures and using variables of pointer to functions

基本上,我想輸入文本字符串,如果它與結構(* cmd_name)上的字符串匹配,則程序將調用並執行與之對應的函數。 這是我的嘗試:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void new_cmd()
 {
     printf("You entered new_cmd function!");
 }
void close_cmd()
 {
     printf("You entered close_cmd function!");
 }
 void open_cmd()
 {
     printf("You entered open_cmd function!");
 }
 void close_all_cmd()
 {
     printf("You entered the close_all_cmd function!");
 }

struct{
    char *cmd_name;
    void (*cmd_pointer)(void);              //variable of a pointer to a function
     }file_cmd[]= {  {"new",      new_cmd},
                  {"open",    open_cmd},
                  {"close",    close_cmd},
                  {"close all",   close_all_cmd}};


int main()
{
   int i;
   char my_string[15];

   scanf("%s",my_string);
   for(i=0; i<4;i++)
      if(file_cmd[i].cmd_name == my_string)       //matching the string
       {
           file_cmd[i].cmd_pointer();            //possible mistake here, trying to open the function
           break;
       }  

    return 0; 
}

每當我對此進行測試並在命令行“ new”或任何字符串上進行編寫時,該程序根本不會執行並退出。

您不能使用==比較字符串 ,而必須使用strcmp()

也就是說, scanf("%s",my_string); 最好是scanf("%14s",my_string); 避免由於輸入超出預期而導致緩沖區過低。 另外,您應始終檢查scanf()的返回值以確保成功。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM