我基本上试图自己编程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");
}
}
正如您从代码中间的注释中看到的那样,我在那时遇到了分段错误,而且老实说我真的不确定它为什么会发生。应该有足够的内存可用。我错误地指点指针吗?如果是这样,我应该如何改变它以使其发挥作用?
答案 0 :(得分:0)
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
分配了错误的空间,并且没有空格。你想要:
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++;
为该附加字符串的内容分配一个字符串和空格的空间。