对于一个更大的程序,我试图在每n个字符后分割一个字符串。例如,理想情况下我应该看到类似的东西:
$ ./split
str = this is a test that I am doing. No need to panic. This is just a test.
=>this <=
=>is a <=
=>test <=
=>that <=
=>I am <=
=>doing<=
=>. No <=
=>need <=
=>to pa<=
=>nic. <=
=>This <=
=>is ju<=
=>st a <=
=>test.<=
相反,我看到以下输出:
$ ./split
str = this is a test that I am doing. No need to panic. This is just a test.
Segmentation fault: 11
我一直盯着这段代码,但不能为我的生活找到分段错误的原因。任何帮助将不胜感激。谢谢!这是源代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **format(char *encoded_image, int encoded_image_size, int split) {
int line_count = encoded_image_size / split + 1; /* One extra line for NULL */
char **lines = malloc(sizeof(char *) * line_count);
for(int iter = 0; iter < line_count - 1; ++iter) {
lines[iter] = malloc(split);
lines[iter] = memcpy(lines[iter], encoded_image[split * iter], split);
printf("%s\n", lines[iter]);
}
lines[line_count] = NULL;
return lines;
}
int main() {
char *str = strdup("this is a test that I am doing. No need to panic. This is just a test.");
printf("str = %s\n\n", str);
char **lines = format(str, strlen(str), 5);
for(int iter = 0; lines[iter] != NULL; ++iter) {
printf("=>%s<=\n", lines[iter]);
}
return 0;
}
(理想输出中可能存在拼写错误,因为我必须手动完成)。 (修正了下面评论中指出的for循环中的错误)