我不停地傳入並返回dirs_later_array。當我在else塊中得到「new_size = ...」時,我第二次得到2的new_size。到現在爲止還挺好。但是當我做一個reallocRealloc不調整指針數組大小
dirs_later_array = realloc(dirs_later_array,
new_size * sizeof(struct dirs_later*));
sizeof保持在4,指針的大小,爲dirs_later_array。我可以成功存儲在dirs_later_array [1]中,但是在下一次進入函數時該值會被覆蓋。
struct dirs_later** add_struct(const char *findme, struct dirent *dptr, struct stat *this_lstat, char *relative_path, const char *type_str, struct dirs_later **dirs_later_array) { struct dirs_later *new_dir = malloc(sizeof(struct dirs_later)); check_realloc_dirs_error(new_dir); if (strcmp(dptr->d_name, ".")) { //Dir and not same directory //Copy the relative path to the struct char *relative_path2; relative_path2 = malloc(strlen(relative_path) + 1); check_realloc_error(relative_path2); strcpy(relative_path2, relative_path); //if (strlen(relative_path) > 0) // relative_path2[strlen(relative_path) - 1] = '\0'; if (NULL != new_dir) { new_dir->findme = findme; new_dir->dptr = dptr; new_dir->st_mode = this_lstat->st_mode; new_dir->relative_path = relative_path2; new_dir->type_str = type_str; } int new_size = 0; /* //Check if this is the first element in the struct if (sizeof(dirs_later_array)/sizeof(struct dirs_later*) == 1) { new_size = 1; } */ if (dirs_later_array == NULL) { dirs_later_array = malloc(sizeof(struct dirs_later*)); //Store the directory structures or process later check_realloc_arr_error(*dirs_later_array); new_size = 1; } else { //Add directories to directories array new_size = (((sizeof(dirs_later_array) + sizeof(struct dirs_later*)))/sizeof(struct dirs_later*)); //printf("new size: %d",new_size); } dirs_later_array = realloc(dirs_later_array, new_size * sizeof(struct dirs_later*)); check_realloc_arr_error(dirs_later_array); dirs_later_array[new_size - 1] = new_dir; } return dirs_later_array; }
'realloc'does不調整任何它只是分配動態內存特殊作爲參數引用並將其分配給您的指針。 – 2012-02-28 07:37:04
@Als但它確實!它調整大小! – 2012-02-28 07:41:18
@Als - 任何也可以確保原始內容保持不變(只要有新的空間量) – 2012-02-28 07:43:58