【问题标题】:Working with malloc, char array and pointer使用 malloc、char 数组和指针
【发布时间】:2015-05-25 23:38:00
【问题描述】:

我试图了解 malloc 和字符数组(c 样式)是如何工作的。考虑以下代码,

// Example program
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;

int main()
{
  //section1: Init  
  char line0[10] = {'a','b','c','d','e','f','g','h','i','j'};
  char line1[10] = {'z','y','x','w','v','u','t','s','r','q'};

  //section2: Allocate Character array
  char* charBuffer = (char*) malloc(sizeof(char)*10);
  cout<<sizeof(charBuffer)<<endl;

  //Section3: add characters to the array
  for (int i=0;i<10;i++)
  {
   *&charBuffer[i] = line0[i];
  }
  //Section4:-add character to array using pointers
  for (int i=0;i<15;i++)
  {
   charBuffer[i] = line1[i%10];
  }
  //section5:-address of characters in the array
  for (int i=0;i<15;i++)
  {
   cout<<"Address of Character "<<i<<" is: "<<&charBuffer[i]<<"\n";
  }
  char *p1;
  p1 = &charBuffer[1];
  cout<<*p1<<endl;
  cout<<charBuffer<<endl;
  free(charBuffer);
  return 0;
}

输出:-

8
Address of Character 0 is: zyxwvutsrqzyxwv
Address of Character 1 is: yxwvutsrqzyxwv
Address of Character 2 is: xwvutsrqzyxwv
Address of Character 3 is: wvutsrqzyxwv
Address of Character 4 is: vutsrqzyxwv
Address of Character 5 is: utsrqzyxwv
Address of Character 6 is: tsrqzyxwv
Address of Character 7 is: srqzyxwv
Address of Character 8 is: rqzyxwv
Address of Character 9 is: qzyxwv
Address of Character 10 is: zyxwv
Address of Character 11 is: yxwv
Address of Character 12 is: xwv
Address of Character 13 is: wv
Address of Character 14 is: v
y
zyxwvutsrqzyxwv

我想了解以下内容,

  1. 为什么 charBuffer 的大小是 8(见输出的第一行),虽然我分配了 10 的大小?
  2. 为什么我可以向 charBuffer 添加 15 个字符,尽管我使用 malloc 只为 10 个字符分配了内存? (参见代码第 4 节)
  3. 为什么在第 5 节的输出中打印的是参考索引之后的字符而不是相应字符的地址?
  4. 如何找到单个字符的地址?
  5. 当字符数组的元素被填满时,是否可以知道数组的大小?例如在第 3 节的循环中显示 sizeof(charbuffer),我们应该得到 1,2,3..,10?

【问题讨论】:

  • 天啊...每个问题一个问题,拜托!!
  • @LightnessRacesinOrbit 很抱歉。但是,当上下文相同时,可以发布 5 个背靠背问题吗?

标签: c++ arrays pointers char malloc


【解决方案1】:

虽然我分配了 10 的大小,为什么 charBuffer 的大小是 8(见输出的第一行)?

不是。您打印出指向该缓冲区的指针的大小。

为什么我可以向 charBuffer 添加 15 个字符,尽管我使用 malloc 只为 10 个字符分配了内存?

你不是。但是,相反,允许计算机不会特意通知您您的错误。你违反了记忆规则。

为什么在第 5 节的输出中打印的是参考索引之后的字符而不是相应字符的地址?

因为将char* 插入流会触发格式化插入,因此流假定您正在流式传输C 字符串。嗯,你是

如何找到单个字符的地址?

您可以写static_cast&lt;void*&gt;(&amp;charBuffer[i]) 来避免这种特殊情况处理并打印出地址。

当字符数组的元素被填满时,是否可以知道数组的大小?例如在第 3 节的循环中显示 sizeof(charbuffer),我们应该得到 1,2,3..,10?

数组的大小永远不会改变,只会改变你写入新值的元素的数量。您可以使用计数器变量自行跟踪。

【讨论】:

  • 非常感谢您的回答!再澄清一点。对于问题1,有什么方法可以找到malloc在堆中分配的内存块的大小?
  • “你就是。” - 他不是因为他的代码中没有 C 字符串,只是一个非终止字符数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多