无法复制字符串

时间:2012-02-28 00:41:43

标签: c

我在调试器中设置了这些变量:

//调试器值不是代码

relative_path =" ./ bin / Debug"

strlen的(RELATIVE_PATH)= 11

relative_path [11] = 0' \ 000' //如Eclipse调试器中所示

在我的代码中,我会这样做:

//**My Code**
struct dirs_later {
    const char *findme;
    struct dirent *dptr;
    struct stat this_lstat;
    char *relative_path;
    const char *type_str;
    DIR * dir;
};

....
struct dirs_later *new_dir = malloc(sizeof(struct dirs_later*));
...
char *relative_path2 = strdup(relative_path);
if (NULL != new_dir) {
    new_dir->findme = findme;
    new_dir->dptr = dptr;
    new_dir->this_lstat = *this_lstat;
    new_dir->relative_path = relative_path2;
     new_dir->type_str = type_str;
    }

但是调试器显示在new_dir-> relative_path = relative_path2之后。然后在调试器中:

//调试器值不是代码

relative_path2 ="& \ 275 \ 001"和

strlen(relative_path2)= 3

我也在我的代码中试过这个:

//**My Code**
char *relative_path2 = malloc(strlen(relative_path) + 1 * sizeof(char));
//check for NULL
strcpy(relative_path2, relative_path);

我得到了相同的结果

1 个答案:

答案 0 :(得分:2)

该行

struct dirs_later *new_dir = malloc(sizeof(struct dirs_later*)); 

struct dirs_later *new_dir = malloc(sizeof(struct dirs_later)); 

因为你想在堆上为结构创建空间,而不仅仅是指针。