简体   繁体   English

尝试在 C 中填充字符串数组时出现分段错误

[英]Segmentation Fault when trying to populate array of strings in C

    
int main() {
    const char* text = "the quick brown fox jumps";
    int* argc = 0;
    char *argv[] = {};
    printf("%d", parse_command(text, argc, argv));
}

int parse_command(const char *inp, int *argc, char *argv[]) {
    int offset = 0;
    int count = 0;

    int i = 0;
    bool bool1 = true;
    while (*(inp + offset) != '\0') {
        if (inp[i] == ' ')
            bool1 = true;

        if (bool1 && inp[i] != ' ') {
            bool1 = false;
            argv[i] = &inp[i];
            ++count;
        }
        ++offset;
        i++;
    }
    *argc = count;
    return count;
}

I am trying to split the character array inp into words, and return the number of words.我正在尝试将字符数组 inp 拆分为单词,并返回单词数。 What is considered a word is: a sequence of non-blank characters ending in one or more blank spaces.被认为是一个词是:以一个或多个空格结尾的非空白字符序列。 I want argc to be set to the number of words (which I think works fine), and argv[0] should point to the first character of the first word, argv[1] to the first character of the second word, and so on.我希望将 argc 设置为单词数(我认为这很好),并且 argv[0] 应该指向第一个单词的第一个字符, argv[1] 指向第二个单词的第一个字符,所以上。

I keep getting segmentation fault error.我不断收到分段错误错误。 Is this because char* argv[] is empty when initialized?这是因为 char* argv[] 在初始化时为空吗? If so, how can I initialize it to a specific length?如果是这样,我怎样才能将它初始化为特定的长度?

When you declare int *argc = 0 you are creating a pointer , and setting its value to 0.当您声明int *argc = 0时,您正在创建一个指针,并将其值设置为 0。

Then dereferencing this pointer is invalid as it is a null pointer, which results in a segfault.然后取消引用这个指针是无效的,因为它是一个 null 指针,这会导致段错误。

What you can do is create an integer (int argc = 0) and pass it by reference to the function (&argc).您可以做的是创建一个 integer (int argc = 0) 并通过引用 function (&argc) 来传递它。

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

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