简体   繁体   English

结构数组和使用函数指针的变量

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

Basically I want to input a string of text and if it matches with the string on the structure (*cmd_name), the program will then call and execute the function that corresponds to it. 基本上,我想输入文本字符串,如果它与结构(* cmd_name)上的字符串匹配,则程序将调用并执行与之对应的函数。 Here's my attempt: 这是我的尝试:

#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; 
}

Whenever I test this and write on the command line "new" or any string, the program doesn't execute at all and exits. 每当我对此进行测试并在命令行“ new”或任何字符串上进行编写时,该程序根本不会执行并退出。

You can not compare strings using == , you have to use strcmp() . 您不能使用==比较字符串 ,而必须使用strcmp()

That said, scanf("%s",my_string); 也就是说, scanf("%s",my_string); should better be scanf("%14s",my_string); 最好是scanf("%14s",my_string); to avoid buffer overlow by longer-than-expected input. 避免由于输入超出预期而导致缓冲区过低。 Also, you should always check the return value of scanf() to ensure success. 另外,您应始终检查scanf()的返回值以确保成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM