如何在特定的内存位置创建数组? c

发布于 2025-01-21 18:14:50 字数 627 浏览 3 评论 0原文

char string1[] = "dog";
char *string2 = string1 + strlen(string1) + 1;
printf("address of string1: %p\n", string1);
printf("address of string2: %p\n", string2);
string2 = malloc(sizeof(char)*4);
string2[0] ='c';string2[1] ='a';string2[2] ='t';string2[3] ='\0';
printf("address of string2: %p\n", string2);

字符串的地址1:0000000061FE14
字符串的地址2:000000000061FE18
字符串的地址2:00000000000000AD4D50

我想在内存位置0x61fe18,

即使我设法 在“ dog \ 0”之后,我想在内存位置0x61fe1。成功获得String2的所需内存位置2,Malloc函数重新分配了该位置。我希望“ CAT”数组从0x61Fe18开始,但是Malloc将其重新分配到0xad4d50

是否有办法将数组分配到所需的起始位置?

char string1[] = "dog";
char *string2 = string1 + strlen(string1) + 1;
printf("address of string1: %p\n", string1);
printf("address of string2: %p\n", string2);
string2 = malloc(sizeof(char)*4);
string2[0] ='c';string2[1] ='a';string2[2] ='t';string2[3] ='\0';
printf("address of string2: %p\n", string2);

address of string1: 000000000061FE14
address of string2: 000000000061FE18
address of string2: 0000000000AD4D50

I want to make a 'cat' string at a memory location 0x61FE18, right after "dog\0"

Even though I've managed to successfully get the desired memory location of string2, the malloc function reassigns the location. I want the "cat" array to start at 0x61FE18 but malloc reassigns it to 0xAD4D50

Is there a way to allocate array to a desired starting location?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

韶华倾负 2025-01-28 18:14:51

你的意思是这样吗?

unsigned char *data = malloc(1000);
if (data) {
    strcpy((char*)data, "cat"); // `data` points to "cat" followed by garbage
    strcpy((char*)data + 4, "dog"); // `data` points to "cat\0dog" garbage
    (int*)(data+24) = 0x01020304; // `data` points to "cat\0dog\0XXXXXXXXXXXXXXXX\1\2\3\4"
                                  // depending on endianness and sizeof int
    free(data);
}

you mean something like this?

unsigned char *data = malloc(1000);
if (data) {
    strcpy((char*)data, "cat"); // `data` points to "cat" followed by garbage
    strcpy((char*)data + 4, "dog"); // `data` points to "cat\0dog" garbage
    (int*)(data+24) = 0x01020304; // `data` points to "cat\0dog\0XXXXXXXXXXXXXXXX\1\2\3\4"
                                  // depending on endianness and sizeof int
    free(data);
}
慈悲佛祖 2025-01-28 18:14:51

如何在特定的内存位置创建数组? C

有没有办法将数组分配给所需的起始位置?

没有标准方式。

How do you create an array in a specific memory location? C

Is there a way to allocate array to a desired starting location?

No standard way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文