【问题标题】:Array of structures and using variables of pointer to functions结构数组和使用函数指针变量
【发布时间】:2016-08-31 06:27:56
【问题描述】:

基本上我想输入一个文本字符串,如果它与结构上的字符串(*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”或任何字符串上写入时,程序根本不会执行并退出。

【问题讨论】:

标签: c string variables pointers structure


【解决方案1】:

你不能使用==比较字符串,你必须使用strcmp()

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

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多