【问题标题】:String declaration segmentation fault字符串声明分段错误
【发布时间】:2016-12-04 09:37:15
【问题描述】:

声明一个字符串后,我得到一个分段错误。 我不知道如何解决这个错误——你能解释一下吗?

代码版本 1(使用来自 cs50.htypedef char *string;):

int main (int argc, string argv[])
{
    string key = argv[1]; 
    checkKey(key, argc);
}

int checkKey(string text, int n)
{
    //check if text is alphabetical and if argc has the desired amount of command-line elements 
}

代码版本 2:

#include <stdio.h>
#include <ctype.h>
#include <cs50.h>

int main (int argc, char* argv[])
{
    printf("%d elements in argc and %s in argv[1]\n", argc, argv[1]);
    char* key = argv[1];
}

【问题讨论】:

  • string 在哪里声明?是 C++ 吗?还是typedef?当你调用你的 main 时,你会传递参数吗?
  • 您是否在某处定义了string?你怎么称呼你的程序?如果没有参数,argv[1] 将无效。
  • 在访问任何argv之前检查argc
  • 字符串在 cs50.h 中定义(基本上是一个 char*),我会在假设 argv[1] 有一些内容之前检查 argc。感谢您的投入。
  • string 是 typedef ,即 char*

标签: c segmentation-fault cs50


【解决方案1】:

如果你在没有命令行参数的情况下运行你的程序,它会接收到 1 的值 argc 和一个大小为 2 的数组 argv,程序的名称在 argv[0]NULL 在 @987654326 @。

如果您的函数 charkKey() 取消引用它作为第一个参数接收的指针,您将调用未定义的行为,这可能会导致分段错误。

【讨论】:

    猜你喜欢
    • 2011-02-22
    • 2016-12-05
    • 2012-11-14
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    相关资源
    最近更新 更多