C:二维字符串数组分段错误

C: 2-Dimensional String Array Segmentation Fault

尝试制作一个小程序,将大字符串中的单词分开,并将(大字符串的)每个单词存储在字符串(即指针)中的字符串数组(即指针)中;形成一个二维字符串数组。 单词分隔符只是一个空格(ASCII 中的 32);大字符串是:


"Showbizzes Oxygenized Equalizing Liquidized Jaywalking"

注:


还有一点,指针数组中的最后一个指针必须包含 0(即 1 个字符:'\0')(这完全是任意的)。


这是程序,没什么特别的,但是...

#include <stdio.h>
#include <stdlib.h>

int main(void) {

    // The string that we need to break down into individual words
    char str[] = "Showbizzes Oxygenized Equalizing Liquidized Jaywalking";

    // Allocate memory for 6 char pointers (i.e 6 strings) (5 of which will contain words)
    // the last one will just hold 0 ('[=10=]')
    char **array; array = malloc(sizeof(char *) * 6);

    // i: index for where we are in 'str'
    // r: index for rows of array
    // c: index for columns of array
    int i, r, c;

    // Allocate 10 + 1 bytes for each pointer in the array of pointers (i.e array of strings)
    // +1 for the '[=10=]' character
    for (i = 0; i < 6; i++)
        array[i] = malloc(sizeof(char)*11);

    // Until we reach the end of the big string (i.e until str[i] == '[=10=]');
    for (i = 0, c = 0, r = 0; str[i]; i++) {

        // Word seperator is a whitespace: ' ' (32 in ASCII)
        if (str[i] == ' ') { 

            array[c][r] = '[=10=]';     // cut/end the current word
            r++;                    // go to next row (i.e pointer)
            c = 0;                  // reset index of column/letter in word
        }

        // Copy character from 'str', increment index of column/letter in word
        else { array[c][r] = str[i]; c++; }

    }   

    // cut/end the last word (which is the current word)
    array[c][r] = '[=10=]'; 

    // go to next row (i.e pointer)
    r++; 

    // point it to 0 ('[=10=]')
    array[r] = 0; 



// Print the array of strings in a grid - - - - - - - - - - - - - - 

    printf("       ---------------------------------------\n"); 
    for (r = 0; r < 6; r++) {

        printf("Word %i --> ", r);
        for (c = 0; array[c][r]; c++)
            printf("| %c ", array[c][r]);

        printf("|");printf("\n");
        printf("       ---------------------------------------");
        printf("\n");
    }

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    return 0;
}

..有问题,我不知道如何解决。


出于某种原因,它复制到字符串数组(即指针)中的第一个字符串(即指针),大字符串的前 6 个字符,然后在第 7 个它给出 分段错误。我已经分配了 6 个指针,每个指针有 11 个字节。至少我认为代码就是这样做的,所以我真的不知道为什么会这样......

希望有人能提供帮助。

将所有出现的 array[c][r] 替换为 array[r][c]

第一个维度是行。

下次你可以使用调试器检查这个:

Program received signal SIGSEGV, Segmentation fault.
0x00000000004007ea in main () at demo.c:37
37  array[c][r] = str[i];