繁体   English   中英

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

[英]C: 2-Dimensional String Array Segmentation Fault

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


“ Showbizzes氧化均衡化液化的人行横道”

注意:

  • 单词全都是10个字符
  • 字符串的总长度为54个字符(包括空格)
  • 缓冲区的总大小为55个字节(包括“ \\ 0”)

还有一点,指针数组中的最后一个指针必须包含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 ('\0')
    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 '\0' 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] == '\0');
    for (i = 0, c = 0, r = 0; str[i]; i++) {

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

            array[c][r] = '\0';     // 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] = '\0'; 

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

    // point it to 0 ('\0')
    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[r][c]替换array[c][r]所有出现

第一维是行。

下次您可以使用调试器进行检查:

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

暂无
暂无

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

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