I have a problem with reallocating an array. I want to save inputs to a string array and realloc it with every new entry. Heres my function:
我有重新分配数组的问题。我想将输入保存到字符串数组并使用每个新条目重新分配它。继承我的职责:
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++;
}
1 个解决方案
#1
1
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++;
}
#1
1
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++;
}