字符串声明分段错误

问题描述:

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

代码版本1(使用typedef char *string;cs50.h):

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]; 
} 
+1

“string”声明在哪里?它是C++吗?或typedef?而当你打电话给你的主要你传递参数? –

+0

你定义了'string'somewhere?你怎么称呼你的程序?如果没有参数,argv [1]将无效。 – Gerhardh

+2

在访问任何'argv'之前检查'argc'。 –

如果你不使用命令行参数运行您的程序,它收到argc和价值1数组argv,大小为2,程序名称为argv[0]NULL,在argv[1]

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