我真的不知道这是否是我问题的正确标题,但我会尝试解释我的问题:
我正在开发一个搜索所有字符串置换的程序,并将这些字符串保存在char**
数组中。
一切看起来都不错,但是程序花费太多时间完成,这是因为realloc
调用太多而且需要花费太多时间。我在这里谈论13700个电话:
for ( size_t i = 0; i < SIZE_2D; i++ ){ // SIZE_2D == 13700
multi[i] = calloc(LINELENGTH, sizeof(char));
}
可以在一次通话中调用char**
上的realloc吗?
就像这里的例子:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int *arr;
unsigned int row = 5, col = 10;
arr = malloc(sizeof *arr * row * col);
if(arr == NULL){
printf("Error, malloc\n");
exit(3);
}
free(arr);
}
这是工作代码:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE_2D 13700
#define LINELENGTH 8
void swap (char *x, char *y);
void permute(char *arr, char *ptr, size_t i, size_t n);
int compare(const void *a, const void *b);
void resizeBuffer ( char **arr, size_t length );
void resultFound( char **multi, char *buffer, size_t length );
//char multi[20240][50] = {0};
int main(void){
char str[] = "abcdefg";
char *arr = calloc(100000, sizeof(char));
char *multi[14000];
//char **multi = calloc(10240, sizeof(char*));
for ( size_t i = 0; i < SIZE_2D; i++ ){
multi[i] = calloc(LINELENGTH, sizeof(char));
}
permute( arr, str, 0, strlen( str ) );
resizeBuffer ( &arr, strlen( arr ) + 1 );
resultFound(multi, arr, strlen( arr ) );
free( arr );
for ( size_t i = 0; i < SIZE_2D; i++ ){
free(multi[i]);
}
}
void resultFound( char **multi, char *buffer, size_t length ){
printf("ARR LENGTH = %zu\n", length);
size_t i = 0;
char *ptr = buffer;
size_t p = 0;
size_t a = 0;
char *tmp = calloc(length + 1, sizeof(char));
size_t count = 0;
while ( i < length ){
if ( ptr[i] == '\n' ){
if ( count != 0){
//printf("Line Found! <-> Line Length = %zu <-> TMP = %s\n",count, tmp);
strcpy(multi[a++], tmp);
memset(tmp, 0, length);
count = 0;
p = 0;
}else{
//printf("Empty Line Found, Ignore it\n\n");
}
}else{
count++;
tmp[p++] = ptr[i];
}
i++;
}
for (size_t l = 0 ; l < a ; l++ ){
printf("Multi[%zu]\t= %s\n",l , multi[l]);
}
free(tmp);
}
void swap (char *x, char *y){
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *arr, char *ptr, size_t i, size_t n){
size_t j;
static char prev[80] = "";
if (i == n){
if (strcmp(prev, ptr)) {
strcat (arr, ptr);
strcat (arr, "\n");
strcpy(prev, ptr);
}
}else{
for (j = i; j <= n; j++)
{
swap( (ptr + i), (ptr + j) );
permute(arr, ptr, i+1, n);
swap( (ptr + i), (ptr + j) );
}
}
}
void resizeBuffer ( char **buffer, size_t length ){
*buffer = realloc(*buffer, (length)* sizeof(char) );
}