将指针到字符串的字符串复制到动态数组中

时间:2011-08-24 15:49:26

标签: arrays dynamic

继我之前的一个问题之后:

Copying a string from a pointer to a string

我现在正在尝试将复制的字符串添加到动态数组中,该数据会根据SD卡上的文件数逐渐增加,并且在换出卡后会被删除。

编辑:此代码第一次正常工作。更改SD卡的内容后,将调用reReadSD()函数并释放fileList。读取SD卡的新内容并将新值写入fileList,但是,在从fileList打印出名称时,我得到符号而不是正确的名称。我认为这是一个错误的释放fileList并重新初始化它,因为相同的代码块在系统上电时工作(当第一次调用reReadSD时)。任何人都可以对此有所了解吗?

编辑:更新的代码

void reReadSD()
{
    free(fileList);
    files_allocated=0;
    num_files=0;
    reRead_flag=0;


    if(f_mount(0, &fatfs ) != FR_OK ){
        /* efs initialisation fails*/
    }//end f_mount 

    FRESULT result;
    char *path = '/'; //look in root of sd card
    result = f_opendir(&directory, path);   //open directory
    if(result==FR_OK){
        for(;;){
            result = f_readdir(&directory, &fileInfo); //read directory
            if(result==FR_OK){
                if(fileInfo.fname[0]==0){break;} //end of dir reached escape for(;;)
                if(fileInfo.fname[0]=='.'){continue;} //ignore '.' files
                TCHAR* temp;
                temp = malloc(strlen(fileInfo.fname)+1);
                strcpy(temp, fileInfo.fname);
                AddToArray(temp);
            }//end read_dir result==fr_ok
        }//end for(;;)
    }//end open_dir result==fr_ok
}//end reReadSD

和..

void AddToArray (TCHAR* item)
{
    u32 delay; 
    if(num_files == files_allocated)
    {

            if (files_allocated==0)
                    files_allocated=5; //initial allocation
            else
                    files_allocated+=5; //more space needed 

            //reallocate with temp variable
            void *_tmp = realloc(fileList, (files_allocated * sizeof(TCHAR*)));

            //reallocation error
            if (!_tmp)
            {
                    LCD_ErrLog("Couldn't realloc memory!\n");
                    return;
            }

            // Things are looking good so far
            fileList = _tmp;
    }//end num_files==files_allocated
    fileList[num_files] = item;
    num_files++;
}//end AddToArray

其中

TCHAR **fileList;
u32 num_files=0;
u32 files_allocated=0;

1 个答案:

答案 0 :(得分:0)

Realloc返回指向重新分配的内存块的指针,该内存块可能与ptr参数或新位置相同。因此,请致电:

void *_tmp = realloc(fileList, (files_allocated * sizeof(TCHAR*)));
如果在新位置分配内存,

将不会更新fileList指针。新文件列表的地址实际存储在_tmp中,因此您必须执行以下操作:

fileList = (TCHAR *) _tmp;
致电realloc

另外,我不太明白

的含义
if (files_allocated == 0)
     files_allocated = 1; //initial allocation
else
     files_allocated++; //more space needed 

这不总是做同样的事情吗?