问题
I have a binary file where I store numbers as strings in this fashion: 11 43 89 101 etc
I want, by using only system commands, to read the numbers stored and store them in a string dynamic array, because i don't know how long the strings will end up being or how many. Here is the relevant code:
char **positions;
int all_names=0,i,j;
fd=open(argv[2],O_RDWR|O_CREAT,S_IRWXU);
i=0;
j=0;
do{
positions=(char**)malloc(sizeof(char*));
(*positions)[i]=(char*)malloc((MAX_SIZE+1)*sizeof(char));
do{
read(fd,positions[i][j],1);
}while(positions[i][j+1]!='\0');
i++;
}while(i<all_names);
for(i=0; i<all_names; i++){
for(j=0; positions[i][j]!='\0';j++){
printf("%c", positions[i][j]);
}
printf("\n");
}
}
All names keeps track of the amount of entries in the binary file.
When I run it I get a segmentation fault. The part where I store the numbers works fine I have checked the file. It always stores the number and a '\0'
after it.
I get this as warning but don't know how to fix it
warning: incompatible integer to pointer conversion passing 'char' to parameter of type 'void *' [-Wint-conversion] read(fd,positions[i][j],1);
About positions[i][j]
.
Thanks for any help
Edit: changed code to:
char **positions;
int all_names=0,i,j;
positions=(char**)malloc(sizeof(char*));
*positions=(char*)malloc((MAX_SIZE+1)*sizeof(char));
fd=open(argv[2],O_RDWR|O_CREAT,S_IRWXU);
i=0;
j=0;
for(i=0; i<all_names; i++){
positions=(char**)realloc(*positions,(all_names) * sizeof(char*));
positions[i]=(char*)malloc((all_names+1)*sizeof(char));
for(j=0; ;j++){
read(fd,&positions[i][j],1);
if (positions[i][j] == ' ') {
break;
}
}
}
for(i=0; i<all_names; i++){
printf("%s\n", positions[i]);
}
}
Now I get an error on runtime:
malloc: * error for object 0x20400036: pointer being realloc'd was not allocated * set a breakpoint in malloc_error_break to debug Abort trap: 6
I really think I am supposed to realloc every time cause all_names value gets updated at an earlier part of my code. What am I doing wrong?
回答1:
You need to check for the null byte after you read, not before.
The second argument to read()
needs to be a pointer to the array element, use &positions[i][j]
.
You have to allocate memory for all the strings, you're just allocating one element of positions
.
positions = malloc(all_names * sizeof(char*));
fd=open(argv[2],O_RDWR|O_CREAT,S_IRWXU);
for(i=0; i<all_names; i++){
positions[i] = malloc((MAX_SIZE+1)*sizeof(char));
for(j=0; ;j++){
read(fd,&positions[i][j],1);
if (positions[i][j] == '\0') {
break;
}
}
}
for(i=0; i<all_names; i++){
printf("%s\n", positions[i]);
}
You also need to set all_names
to the actual number of strings in the file, not 0
. I'm not sure where you get that from.
来源:https://stackoverflow.com/questions/59036963/store-data-from-binary-file-into-dynamic-array-of-strings