[英]C: 2-Dimensional String Array Segmentation Fault
嘗試制作一個小程序,將大字符串中的單詞分隔開,並將(大字符串中的)每個單詞存儲在字符串(即指針)數組中的字符串(即指針)中; 形成一個二維字符串數組。 單詞分隔符只是一個空格(ASCII中為32)。 大字符串是:
“ Showbizzes氧化均衡化液化的人行橫道”
注意:
還有一點,指針數組中的最后一個指針必須包含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.