【问题标题】:C printf array and get open_stackdumpfile errorC printf 数组并得到 open_stackdumpfile 错误
【发布时间】:2014-03-06 07:05:16
【问题描述】:

在用户输入的命令行中:

cmatch -i -n hello test1.in test2.in

“hello”是程序将在输入文件中搜索匹配行的字符串。

现在我被困在 printf 这个字符串上。我是 C 新手,不知道字符串数组是如何工作的。

int main(int argc, char **argv){
       options opts;
       program_name = basename (argv[0]);
       scan_options (argc, argv, &opts);



       int arrLength=argc-optind;
       char *strings[arrLength];
       char *fileNames[arrLength-1];
       const int fileNamesLength=arrLength-1;

       int argi; int i=0;
       for (argi = optind; argi < argc; ++argi) {
          printf ("operand[%d] = \"%s\"\n", argi, argv[argi]); //printing operands
          strings[i]=argv[argi]; //assigning strings
          i++;
       }

       char *stringToMatch=strings[0];
       printf("String to match=%s\n",stringToMatch);

       int f;
   for(f=0; f<fileNamesLength; f++){
       fileNames[f]=strings[f+1];
       printf(fileNames[f]);
   }



       printf("GET THROUGH");

现在的输出是:

操作数[3] = "你好"

操作数[4] = "test1.in"

操作数[5] = "test2.in"

要匹配的字符串 = "hello"

0 [main] cmatch 6092 open_stackdumpfile: Dumping stack trace to cmatch.exe.stackdump

那么 *stringToMatch 有什么问题?

【问题讨论】:

  • optind 设置为什么?我没有看到它在任何地方定义
  • 最后一个-option之后第一个操作数的位置。它是我的老师提供的..
  • 你用的是什么编译器?
  • 我不确定....我在 Eclipse 中编写代码并使用 gcc Run->cmd 编译文件
  • 那么你的编译器就是 GCC。我正在使用 Visual Studio 2013 并测试了您的代码。我必须将3 的常量值分配给optind 并稍微修改代码以解决缺少的功能和不同的语义,但是当我运行它时,我无法重现您的错误。您可以提供更多信息吗?喜欢实际的堆栈跟踪、调用堆栈或更详细的错误信息?

标签: c arrays string printf


【解决方案1】:

要在 C(字符数组)中打印“字符串”,您可以执行以下操作:

printf("%s\n", filenames[f]);

还要比较 c 中的两个字符串,您需要执行以下操作:

#include <string.h>

然后使用函数strcmp如下检查两个字符串是否相等:

if(strcmp(name1, name2)==0)

另外,我建议避免这样的行:

fileNames[f]=strings[f+1];

您可能会访问范围之外的内存。而是将您正在搜索的字符串分配给一个变量并使用它。所以比较部分看起来像这样:

if(strcmp(constname, strings[f])==0)

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    相关资源
    最近更新 更多