2012-02-28 89 views
0

我不停地傳入並返回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; 
} 



+0

'realloc'does不調整任何它只是分配動態內存特殊作爲參數引用並將其分配給您的指針。 – 2012-02-28 07:37:04

+1

@Als但它確實!它調整大小! – 2012-02-28 07:41:18

+0

@Als - 任何也可以確保原始內容保持不變(只要有新的空間量) – 2012-02-28 07:43:58

回答

7

sizeof是編譯時間特徵和只檢查一個表達式的靜態大小。所以對於指針而言,它只會返回平臺上指針的大小。 sizeof不測量動態分配的數據的大小。 C中沒有標準功能來獲取動態分配數據的大小。

+0

所以基本上我需要始終跟蹤數組索引? – user994165 2012-02-28 07:41:35

+1

@ user994165:是的,您需要自己跟蹤動態分配的數據大小。 – 2012-02-28 07:49:19

2

您的sizeof(struct dirs_later*)應改爲sizeof(struct dirs_later) - 和以前一樣!

此外,sizeof是一個編譯時功能。你需要像這樣的結構來保存大小

struct my_dirs 
    struct dirs_later *dirs; 
    int size; 
}; 

初始化像這樣

struct my_dirs directories; 
directories.size = 0; 
directories.dirs = NULL; 

然後添加(注意realloc可以接受NULL作爲參數

directories.dirs = realloc(directories.dirs, 
          (++directories.size) * sizeof(struct dirs_later)); 

這也將簡化你的代碼

相關問題