在这里,我试图编写自己的realloc函数,并坚持将旧数组复制到新数组。如果一个文件每行仅包含16个或更少的字符串,这没有问题。该问题在原始设置16上的行出现时发生。这意味着问题与我认为的realloc函数实现有关。在我的程序中,我设置了三个步骤来控制数组的更改。
我的想法是:
第一步:当文件行小于或等于16时,将值赋给new_array
第二步:当文件的行等于17时,应多分配一个空间。将旧数组复制到新数组,然后将当前行分配到最后一个空格
第三步:类似于第二步,但是旧数组是以前的扩展数组。
现在,我正在努力弄清为什么它不起作用。当我的文件正好有17行时,例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
结果是
here start
1
2
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
17
The file 'foo' had 17 lines.
utitlityFunction.c
#include "utilityFunction.h"
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
char **extendArray(char **oldArray, int oldLen, int newLen){
char **newptr = malloc(newLen * sizeof (char*)); //updated here. No changed for result
// if(newptr == NULL){
// perror("Failed to allocate");
// exit(1);
// }
memcpy(newptr, oldArray, oldLen);
free(oldArray);
return newptr;
}
我的主要功能代码如下。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utilityFunction.h"
int main(int argc, char**argv){
FILE *filename;
size_t len = 0;
char *line = NULL;
int index;
int countLine = 0, i = 0;
char** new_array = malloc(16 * sizeof(char*));
char** extended_array;
char* current_line;
for(index = 1; index < argc; index++){ //loop for all files name you input in the command line
filename = fopen(argv[index], "r");
if(filename == NULL){
printf("The file '%s' did not exist.\n", argv[index]);
}else{
while(getline(&line, &len, filename)!=EOF){
current_line = strdup(line);
if(new_array == NULL){
perror("Failed to allocate");
exit(1);
}
if(i<16){
new_array[i] = current_line;
}
else{
if(i==16){ //actually index 17
extended_array = extendArray(new_array, i, countLine);
extended_array[i] = current_line;
}else{
printf("aaa?\n");
extended_array = extendArray(extended_array, i, countLine);
extended_array[i] = current_line;
}
}
i++;
countLine++;
}
//mprintf("%s\n", extended_array[0]);
//mprintf("-->m%d\n", countLine);
printf("here start\n");
int j;
for(j = 0; j < countLine; j++){
printf("%s\n", extended_array[j]);
}
//print line result after end of file
printf("The file '%s' had %d lines.\n", argv[index], countLine);
}
}
}
我只是失去了....
我认为您的问题来自于memcpy。void * memcpy(void *目标,const void *源,size_t num); 您需要一次调用一次标签中的每种情况,而不是char **。尝试一下
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句