【发布时间】:2021-12-20 21:54:31
【问题描述】:
当我尝试一次将一个字符从一个大字符 [] 复制到一个字符**时,我遇到了一个奇怪的错误。我需要将文本分成 16 个块并将它们存储在一个数组中,我的想法是我必须获取文本大小并获取块的数量。当我尝试在最后复制数组的每一行中的 16 块时,我得到 Exception has occurred。分段故障。 作为示例文本,这里是代码:
#include <stdio.h>
#include <string.h>
int main() {
char simpleText[] = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
int size = strlen(simpleText);
int chunks = size / 16;
int r = size % 16;
char** screen = (char**) malloc(chunks * sizeof(char*));
for (int i = 0; i < chunks; i++) {
screen[i] = (char*) malloc (16 * sizeof(char));
}
int counter = 0;
int row = 0;
for (int i = 0; i < size; i++) {
char c = simpleText[i];
screen [row][counter] = c;
counter++;
if (counter == 16 || i == size) {
screen[row][counter] = '\0';
counter = 0;
row++;
}
}
printf("=========================================================\n");
}
当这一行的第 35 行时代码失败:screen [row][counter] = c;。我四处搜索,但似乎无法理解为什么会失败。
【问题讨论】:
-
int chunks = size / 16;除非size是 16 的精确倍数,否则这会比所需的块少一个。如果r不为 0,则需要加 1。跨度> -
好的,所以我需要做这样的事情吗?尺寸 = ((尺寸 % 16 )== 0) ?尺寸/16:(尺寸/16)+ 16;
-
示例:
if (r != 0) chunks++;不要更改size,因为它需要保持输入字符串的长度。 -
哦,我明白了,谢谢!
-
现在您在分配的缓冲区之外写入 1 个字符