尝试制作一个小程序,将大字符串中的单词分隔开,并将(大字符串中的)每个单词存储在字符串(即指针)数组中的字符串(即指针)中;形成一个二维字符串数组。 单词分隔符只是一个空格(ASCII中为32)。大字符串是:
“ Showbizze充氧均衡化液化人行横道”
注意:
还有一件事,指针数组中的最后一个指针必须保留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个字节。.至少那就是我认为代码正在执行的操作,所以我真的不知道为什么会发生这种情况...
希望有人可以提供帮助。
答案 0 :(得分:2)
将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];