我基本上是在尝试自己编写sort
程序,以熟悉 C 语言。由于我正在从一个文件中读取内容,因此我考虑通过将所述文件的内容复制到一个先数组。我需要使用 malloc
和 realloc
来做到这一点。到目前为止,我有这个:
(r 是我稍后会使用的一个选项,但我已经尝试从一开始就集成它)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BUFFER 1024
int main (int argc, char **argv) {
FILE *f;
int ram = 0;
char **save;
int lines=0;
char buff[BUFFER];
size_t size;
int o;
while ((o = getopt(argc, argv, "r")) != -1) {
switch (o) {
case 'r': ram++; break;
case '?': fprintf(stderr, "Invalid arguments\n"); exit(0);
default: printf("Can I even go in here?\n"); break;
}
}
/* argv buildup:
argc == 3:
0 - prog name
1 - opt?
2 - filename
3 - NULL
*/
if (argc > (1 + ram)) {
f = fopen(argv[1 + ram], "r");
if (f == NULL) {
fprintf(stderr, "File does not exist\n");
exit(0);
}
fgets(buff, BUFFER, f);
if (buff != NULL) {
save = malloc(strlen(buff) + 1);
size = strlen(buff) + 1;
/* here's the first segmentation fault */
strcpy(save[lines], buff);
lines++;
} else {
fprintf(stderr, "Either reached end of file or something bad happened\n");
}
while ((fgets(buff, BUFFER, f)) != NULL) {
save = realloc(save, size + strlen(buff) + 1);
size = size + strlen(buff) + 1;
strcpy(save[lines], buff);
lines++;
}
} else {
fprintf(stderr, "Please start up the program correctly\n");
}
}
正如您从代码中间的注释中看到的那样,我当时遇到了段错误,而且老实说我真的不确定为什么会发生这种情况。应该有足够的可用内存。我是否错误地定位了该指针?如果是这样,我应该如何更改它才能使其正常工作?
最佳答案
if (buff != NULL) {
save = malloc(strlen(buff) + 1);
size = strlen(buff) + 1;
/* here's the first segmentation fault */
strcpy(save[lines], buff);
lines++;
} else {
您为保存
分配了错误的空间量,并且没有为字符串分配空间。你想要:
save = malloc (sizeof (char *));
*save = malloc (strlen (buff) + 1);
这会为一个字符串分配空间,并为该字符串的内容分配空间。要添加其他字符串,您需要:
save = realloc (save, (lines + 1) * sizeof (char *));
saves[lines] = malloc (strlen (buff) + 1 );
strcpy (saves[lines}, buff);
lines++;
这会为另外一个字符串分配空间,并为该附加字符串的内容分配空间。
关于C:将文件复制到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33377715/