0

I'm working on an exercise and can't seem to figure out what's going wrong. The prompt reads, "The variable cp_arr has been declared as an array of 26 pointers to char. Allocate 26 character values, initialized to the letters 'A' through 'Z' and assign their pointers to the elements of cp_arr (in that order)."

Edit: this post was flagged as a duplicate to a post involving pointers and strings, this isn't the same issue.

While testing the code, this is what I've come up with, but the output isn't exactly what I was expecting.

#include <iostream>
using namespace std;

int main()
{
    char next = 'A';
    char* cp_arr[26];
    for (int i = 0; i < 26; i++)
    {
        cp_arr[i] = new char(next);
        cout << cp_arr[i] << endl;
        next++;
    }
    system("pause");
}
Nick
  • 29
  • 5
  • Possible duplicate of [cout << with char\* argument prints string, not pointer value](https://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value) – Ryan1729 Oct 26 '19 at 04:54
  • _"the output isn't exactly what I was expecting"_ -- that's nice? But it doesn't really tell us anything useful. What is the output that you were expecting, and what is your actual output? – JaMiT Oct 26 '19 at 05:58
  • You are presuming `-std=c++14` with the use of [placeholder type specifiers](https://en.cppreference.com/w/cpp/language/auto) (2)? – David C. Rankin Oct 26 '19 at 06:15
  • `cp_arr[i]` points at a single dynamically allocated `char` that has a value `'A'` for every `i`. When that is streamed to, `cout`, it is treated as if each `cp_arr[i]` points at the first character of a nul terminated string - despite not being that. The behaviour of every `cout << cp_arr[i]` is therefore undefined. Whatever output you are expecting, there is no guarantee that it will be produced. – Peter Oct 26 '19 at 08:18

1 Answers1

1

cp_arr[i] is a pointer-to-char, which is interpreted (by deeply-embedded convention) as a C string pointer. If you want to output just the one char it points to, do that:

cout << *cp_arr[i] << endl;
jthill
  • 55,082
  • 5
  • 77
  • 137