hal*_*i0n 17 c c++ pointers character
基本问题.
char new_str[]="";
char * newstr;
Run Code Online (Sandbox Code Playgroud)
如果我必须将一些数据连接到它或使用字符串函数如strcat/substr/strcpy,两者之间的区别是什么?
我知道我必须为char*方法分配内存(第2行).我不太确定如何.
const char*和字符串文字是一样的吗?
我需要了解更多.有人能指出一些不错的详尽内容/材料吗?
消除混淆的最佳来源是Peter Van der Linden,专家C编程,Deep C机密 - 数组和指针的不同之处在于它们在内存中的处理方式.
有阵列,
char new_str[];编译器给new_str一个在编译和运行时都知道的内存地址,例如0x1234,因此new_str的索引很简单
[].例如new_str[4],在运行时,代码选择new_str驻留位置的地址,例如0x1234(即物理内存中的地址).通过[4]向其添加索引说明符0x1234 + 0x4,可以检索该值.
然而,使用指针,编译器给出符号
char *newstr地址,例如0x9876,但在运行时,使用的地址是间接寻址方案.假设newstr是malloc'd
newstr = malloc(10);,正在发生的是,每次代码中的引用都使用newstr,因为newstr的地址是编译器已知的,即0x9876,但newstr指向的是变量.在运行时,代码从物理内存0x9876(即newstr)获取数据,但在该地址是另一个内存地址(因为我们将它malloc),例如0x8765它在这里,代码从该内存地址获取数据malloc分配给newstr,即0x8765.
该char new_str[]和char *newstr可以互换使用,因为一个数组的第零个元素的索引衰变为指针,并解释你为什么能newstr[5]或*(newstr + 5)注意如何指针表达式中使用,即使我们已经宣布char *newstr,因此
*(new_str + 1) = *newstr; 要么 *(new_str + 1) = newstr[1];
总之,两者之间的真正区别在于如何在内存中访问它们.
得到这本书并阅读它,然后活着并呼吸它.这是一本精彩的书!:)
这是一个字符数组:
char buf [1000];
Run Code Online (Sandbox Code Playgroud)
所以,例如,这没有任何意义:
buf = &some_other_buf;
Run Code Online (Sandbox Code Playgroud)
这是因为buf虽然它具有类型指针的特征,但它已经指向唯一有意义的地方.
char *ptr;
Run Code Online (Sandbox Code Playgroud)
另一方面,ptr它只是一个指针,可能指向某个地方.大多数情况下,它是这样的:
ptr = buf; // #1: point to the beginning of buf, same as &buf[0]
Run Code Online (Sandbox Code Playgroud)
或者这个:
ptr = malloc (1000); // #2: allocate heap and point to it
Run Code Online (Sandbox Code Playgroud)
要么:
ptr = "abcdefghijklmn"; // #3: string constant
Run Code Online (Sandbox Code Playgroud)
对于所有这些,*ptr可以写入 - 除了第三种情况,其中一些编译环境定义字符串常量是不可写的.
*ptr++ = 'h'; // writes into #1: buf[0], #2: first byte of heap, or
// #3 overwrites "a"
strcpy (ptr, "ello"); // finishes writing hello and adds a NUL
Run Code Online (Sandbox Code Playgroud)