char *变量声明

时间:2015-03-11 22:12:17

标签: char const

我只想验证我做对了。 从sr到ds2的副本给出错误。这是因为ds2被认为是" const" ?? 谢谢,希望这不是一件好事。

#include <stdio.h>
#include <string.h>
#include <malloc.h>

int main(void)
{
    char *sr = "Hello World";
    char *ds1 = (char*)malloc(100 * sizeof(char));
    char *ds2 = "12345678901234567890";

    // This statement works just fine
    printf("%s\n", strcpy(ds1, sr));

    // This gives error
    strcpy(ds2, sr);


    printf("%s\n", ds2);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

这是一篇类似的帖子

difference between char* and char[] with strcpy()

当你这样做时

char *ds2 = "12345678901234567890";

编译器使指针指向不可写的内存区域。

使用此行

// This gives error
   strcpy(ds2, sr);

你正试图在不可写的内存中进行strcpy。

每个malloc都应该有空闲,因为你正在分配内存而不是取消分配内存。