我在unix中运行程序。它有分段错误。我发现它来自 read_names 函数中的 for 循环。当我禁用循环并设置 i = 0 时,它起作用了。但是,当我设置 i = 1 或其他数字时,它再次显示分段错误。我认为我存储字符串的方式可能是错误的。谁能帮我解决这个问题?
此外,我可以使用 strtok 将字符串保存到二维数组中吗?
谢谢你。
#include <stdio.h>
#include <malloc.h>
#include<string.h>
void alloc(char ***surname, char ***first, char **mid_init, int num);
void read_names(FILE *inp, char ***surname, char ***first, char **mid_init, int num );
void free_memory(char ***surname, char ***first, char **mid_init, int num);
int main(int argc, char *argv[])
{
int num;
char **surname, **first, *mid_init;
FILE *inp = fopen(argv[1], "r");
FILE *outp = fopen(argv[2], "w");
char array[79];
fgets(array, 79, inp);
fgets(array, 79, inp);
fgets(array, 79, inp);
printf("%s", array);
fscanf(inp, "%d", &num);
fprintf(outp, "%d \n\n", num+10);
alloc(&surname, &first, &mid_init, num);
read_names(inp, &surname, &first, &mid_init, num);
free_memory(&surname, &first, &mid_init, num);
fclose(inp);
fclose(outp);
return 0;
}
void alloc(char ***surname, char ***first, char **mid_init, int num)
{
int i;
*surname = (char**)malloc(num * sizeof(char*));
*first = (char**)malloc(num * sizeof(char*));
*mid_init = (char*)malloc(num * sizeof(char));
for(i=0; i<num; i++)
{
(*surname)[i] = (char*)malloc(15*sizeof(char));
(*first)[i] = (char*)malloc(10*sizeof(char));
}
}
void read_names(FILE *inp, char ***surname, char ***first, char **mid_init, int num )
{
char *token, array[79];
char delim[6] = ", .\n";
int i=0/*, k=0*/;
printf("loop begins\n");
for(i=0; i<num; i++)
{
fgets(array, 79, inp);
printf("%s\n", array);
fgets(array, 79, inp);
printf("%s\n", array);
token = strtok(array, delim);
strcpy( *(*(surname+i)+0), token);
printf("%s ", *(*(surname+i)+0));
token = strtok(NULL, delim);
strcpy( *(*(first+i)+0), token);
printf("%s ", *(*(first+i)+0));
token = strtok(NULL, delim);
**mid_init = token[0];
printf("%s\n", *mid_init);
}
printf("\nloop ends\n");
}
void free_memory(char ***surname, char ***first, char **mid_init, int num)
{
int i;
free((*mid_init));
for(i=0;i<num;i++)
{
free((*surname)[i]);
free((*first)[i]);
}
}