结构数组和指向函数的指针变量

时间:2016-08-31 06:27:57

标签: c string variables pointers structure

基本上我想输入一个文本字符串,如果它与结构上的字符串匹配(* 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; 
}

每当我测试它并在命令行上写下&#34; new&#34;或任何字符串,程序根本不执行并退出。

1 个答案:

答案 0 :(得分:2)

您无法使用==比较字符串,您必须使用strcmp()

尽管如此,scanf("%s",my_string);最好是scanf("%14s",my_string);,以避免缓冲区因输入超出预期而过度。此外,您应始终检查scanf()的返回值以确保成功。