【问题标题】:Difference between char pointer and char arraychar指针和char数组的区别
【发布时间】:2012-12-05 11:46:15
【问题描述】:

我定义了 2 个变量,一个是指针,一个是数组

char* ptr;
char* array;

ptr = "12345";
array = new int[5];

for(int i = 0; i < 5; i++)
    array[i] = i;

while(*ptr != 0)
        cout << *ptr++ << endl;

//Get garbage values
for(int i = 0; i < 5; i++)
    cout << ptr[i];

我想知道变量之间的主要区别是什么。 以及为什么当我尝试打印“ptr []”中的值时得到垃圾值 数组方式,但是在遍历 淡水河谷。我似乎无法理解我的变量“ptr”如何指向 5 字符,因为它应该只能指向一个。

【问题讨论】:

  • 提示:ptr++ 改变了ptr 的值。你永远不会重置它。

标签: c++ arrays pointers


【解决方案1】:

指针和数组有很多区别,但是你得到垃圾的原因是当你使用带有索引的ptr时,它已经指向“12345”的空终止符。

每次你这样做:

*ptr++;

ptr 指向它曾经指向的下一个元素(即 1、2、3、...)。循环结束时,它指向空终止符\0,然后当您尝试使用i 对其进行索引时,它指向未知内存。

我建议您使用临时指针来遍历元素:

const char* ptr; // declaring ptr constant in this case is a good idea as well

...

ptr = "12345";
char *tmp = ptr;

...

while(*tmp != 0)
    cout << *tmp++ << endl;

【讨论】:

  • 有没有办法重置变量而不是进入循环并递减它?
  • @SidharthMudgal:嗯?这段代码定义明确:int main() { const char* ptr = "12345"; }.
  • @SidharthMudgal 它怎么会导致缓冲区溢出?当然它不应该被修改,这就是我建议使用常量指针的原因。
  • 分配字符串指针不像执行 strcpy(),它只是将指针设置为指向不同的位置(在这种情况下,指向可执行文件中字符串“12345”的位置)由编译器静态存储)。
  • @SidharthMudgal:这也很好(尽管在 C++11 中必须是 const char*)。为什么不详细说明导致溢出的原因?
【解决方案2】:

这里真的有三个概念在起作用:指向字符的指针、动态数组和字符串字面量:

    // Initialise a character pointer to point to a dynamic array of characters
    char* array = new char[5];

    // Assign values pointed to.
    for(int i = 0; i < 5; i++)
        array[i] = i;
    // Read back the values.
    for(int i = 0; i < 5; i++)
         std::cout << array[i];

    // Initialise a character pointer to point to a string literal.
    const char* const ptr = "12345";

    const char* charIterator = ptr;
    while(*charIterator != 0)
        std::cout << *charIterator << std::endl;

    //Another way to read values.
    for(int i = 0; i < 5; i++)
        std::cout << ptr[i];

注意const 在表达式const char* const ptr 中的双重使用。第一个意味着字符值是恒定的,第二个是指针本身是恒定的。后者阻止了写入ptr++,并丢失了字符串文字开头地址"12345" 的唯一句柄。

【讨论】:

  • 所以 const char* ptr = ... 导致“12345”永远不会改变。为什么要在 char* 之后添加 const?有什么优势?
  • 如上所述,如果你写ptr++会报错,这就是你得到垃圾值的原因,
【解决方案3】:

如果直接使用指针ptr,ptr存储的指向数组值的地址会发生变化。在这个循环中:

while(*ptr != 0)

   cout << *ptr++ << endl;

现在,ptr 指向数组的末尾(\0)。

也许你应该在上面的循环之前执行最后一个循环。

通常,按照尼克的方式做更合适。

【讨论】:

  • 当 ptr 到达末尾或 \0 并且我打印出该值时,它会显示一个空白空间吗?
猜你喜欢
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 1970-01-01
  • 2021-01-26
  • 2019-09-13
  • 2018-04-05
  • 1970-01-01
相关资源
最近更新 更多