如何解决C strcpy() 指向指针?这是如何工作的?
这是我正在阅读的一本书中的一个示例,用于演示堆内存的使用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
char *char_ptr;
int *int_ptr;
int mem_size;
if (argc < 2) //if not given an argument,defaukt memory size is 50//
mem_size = 50;
else
mem_size = atoi(argv[1]);
printf("\t[+] allocating %d bytes of memory on the heap for char_ptr\n",mem_size); //memory is given,and passed to char pointer//
char_ptr = (char *)malloc(mem_size);
if(char_ptr == NULL) { //check for error//
fprintf(stderr,"Error: Could not allocate memory.\n");
exit(-1);
}
strcpy(char_ptr,"This memory is located on the heap.");
printf("char_ptr (%p) --> '%s'\n",char_ptr,char_ptr);
printf("\t[+] allocating 12 bytes of memory on the heap for int_ptr\n");
int_ptr = (int *)malloc(12);
if(int_ptr == NULL) {
fprintf(stderr,"Error: coud not allocate heap memory.\n");
exit(-1);
}
*int_ptr = 31337;
printf("int_ptr (%p) --> %d\n",int_ptr,*int_ptr);
printf("\t[-] freeing char_ptr's heap memory...\n");
free(char_ptr);
printf("\t[+] allocating another 15 bytes for char_ptr\n");
char_ptr = (char *)malloc(15);
if(char_ptr == NULL) {
fprintf(stderr,"Error: coud not allocate heap memory.\n");
exit(-1);
}
strcpy(char_ptr,"new memory");
printf("char_ptr (%p) --> '%s'\n",char_ptr);
printf("\t[-] freeing int_ptr's heap memor...\n");
free(int_ptr);
}
我对这一行感到困惑:strcpy(char_ptr,"This memory is located on the heap.");
char_ptr
已经包含分配的堆内存的地址,那么这个文本如何被复制到指针中呢?从printf("char_ptr (%p) --> '%s'\n",char_ptr);
来看,似乎分配的堆内存的地址也没有改变。这是否基本上意味着指针包含两个值?这是如何工作的?
kingvon@KingVon:~/Desktop/asm$ ./a.out
[+] allocating 50 bytes of memory on the heap for char_ptr char_ptr (0x55ef60d796b0) --> 'This memory is located on the heap.'
[+] allocating 12 bytes of memory on the heap for int_ptr int_ptr (0x55ef60d796f0) --> 31337
[-] freeing char_ptr's heap memory...
[+] allocating another 15 bytes for char_ptr char_ptr (0x55ef60d79710) --> 'new memory'
[-] freeing int_ptr's heap memor...
[-] freeing char_ptr's heap memory...
解决方法
这是否意味着指针包含两个值?
否 – char_ptr
变量只能有一个特定值 – 这将是(在成功调用 malloc
之后)内存中指定字节数的块的起始地址。就这样——一个地址。
可能让您感到困惑的是,在后续代码中如何使用/解释该地址。
当 strcpy(char_ptr,"This memory is located on the heap.");
行将数据从第二个参数(字符串文字)复制到从该地址开始的字节中时,它会使用该地址 - 并且它会继续这样做直到找到该文字末尾的 nul
-终止符(它也将复制,然后停止)。
printf("char_ptr (%p) --> '%s'\n",char_ptr,char_ptr);
调用更加微妙。尽管您为两个参数提供相同的地址(完全相同),printf
函数对该地址的解释方式由相应的格式参数决定。对于第一个实例,%p
说明符告诉函数打印地址的实际值;对于第二个实例,%s
说明符告诉它按顺序打印出字符,从给定地址开始,并在找到第一个 nul
(零)字符时停止。
strcpy
将一个空终止的 C 字符串复制到第一个参数指向的内存中。
不,它不包含两个值。指针有它自己的值,它是一个内存地址,它指向该内存地址处的值。这可以是一件事,也可以是一系列的事情。在字符指针的情况下,它是数组中的第一个字符。一个 NUL 字符数组,也就是末尾的 0 字符是一个 C 字符串。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。