我有一个重新分配数组的问题。我想将输入保存到字符串数组中,并对每个新条目进行realloc。下面是我的函数:
char** history=0;
int historycounter=0;
void saveHistory(char* input){
history=(char**)realloc(history,sizeof(*history)+sizeof(input)*sizeof(char));
history[historycounter]=(char*)malloc(sizeof(input)*sizeof(char));
strcpy(history[historycounter],input);
historycounter++;
}
try this
void saveHistory(const char *input){
size_t size = strlen(input)+1;
history = realloc(history, sizeof(*history)*(historycounter+1));
history[historycounter] = malloc(size);
memcpy(history[historycounter], input, size);
historycounter++;
}