【问题标题】:Dereferencing array pointers取消引用数组指针
【发布时间】:2016-04-10 20:21:36
【问题描述】:

我试图取消引用这个指向新数组 (ARR) 的指针,但是从下面的这个示例中,当我执行取消引用 *issub 时,它只“携带”第一个字母。我该如何解决这种情况并让ARR(subscount) 成为我想要的词?

#include <iostream>
  int main(){
  char inp[3]={'O','I','L'};
  int lll=3;
  char ARR[3];
  int subscount=0;

  char * issub= new char[lll];
  for(int i=0;i<lll;i++){
    issub[i]=inp[i];
  }
  ARR[subscount]=*issub;
 }

【问题讨论】:

  • 你的代码很糟糕,因为 inp 正在被越界索引访问!
  • 你到底想做什么?填充ARR 的每个单元格,使其与inp 相同,ARR[subscount] 中有一个指针将指向单词?
  • @gsamaras 我希望 ARR[0] 像 inp 一样成为“OIL”
  • 但是@J.Barbosa inp[0] 是“O”,而不是“OIL”。
  • @DavidSchwartz strcpy 不适用于不包含字符串的字符数组(如本问题所示)

标签: c++ string pointers


【解决方案1】:

我觉得你很困惑,所以我为你做了一个例子:

#include <iostream>

int main() {
  char inp[4] = {'O','I','L', '\0'};
  int lll = 4;
  // initialize elements of 'ARR' to 0 for safety
  char ARR[4] = {0};
  int subscount = 0;

  // dynamic allocation, DO NOT forget to de-allocate
  char* issub = new char[lll];
  // copy every element of 'inp' to 'issub'
  for(int i=0;i<lll;i++) {
    issub[i]=inp[i];
  }
  // this will copy where '*issub' points to,
  // that is the 'issub[0]', to 'ARR[subscount]'
  ARR[subscount] = *issub;
  std::cout << ARR << "\n"; // prints: O
  // you can use a for loop as before to copy the contents,
  // from 'inp', 'issub' to 'ARR'

  // However, we will do something different here,
  // so I am de-allocating 'issub'
  delete [] issub;

  // We will use an array of pointers, with size 2,
  // thus it will have two pointers in total.
  char* ptr_arr[2];

  // Assign the first pointer to 'inp'
  ptr_arr[0] = &(inp[0]);

  std::cout << ptr_arr[0] << "\n"; // prints OIL

  // we don't use the second pointer,
  // set it to NULL
  ptr_arr[1] = NULL;
  return 0;
}

希望有所帮助(但它确实让我想起了 C,而不是 C++,应该使用 std::string)。


更新为以空字符结尾的字符串; What is a null-terminated string?

谢谢@M.M

【讨论】:

  • 我想我明白了,但 inp[0] 不应该只是第一个字符吗?
  • @J.Barbosa inp[0] 是第一个字符。是的。
猜你喜欢
  • 1970-01-01
  • 2012-03-25
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2021-03-27
  • 1970-01-01
相关资源
最近更新 更多