char array and pointers

Lost the road somwhere here:
I compiled an example from the book, thus testing pointers as *int. All went well. So i tried to do the same with a char array instead of an int array. But the compiling fails on: "invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]"

Isn't the array concept of char vs int equivalent?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Example with:
// integer array
#include <iostream>
using namespace std;
int main ()
{
  int numbers[5];
  int * p;

  p = numbers;  *p = 10;
  p++;  *p = 20;
  p = &numbers[2];  *p = 30;
  p = numbers + 3;  *p = 40;
  p = numbers;  *(p+4) = 50;
  for (int n=0; n<5; n++)
    cout << numbers[n] << ", ";
  cout << endl;
  return 0;
}


// Example with:
// character array
#include <iostream>
using namespace std;
int main ()
{
  char letters[5];
  char * p;

  p = letters;  *p = "A";
  p++;  *p = "B";
  p = &letters[2];  *p = "C";
  p = letters + 3;  *p = "D";
  p = letters;  *(p+4) = "E";
  for (int n=0; n<5; n++)
    cout << letters[n] << ", ";
  cout << endl;
  return 0;
}
You cannot assign the string to a pointer to string.
Use *p='A'; instead of *p="A";.
Yes, they should be logically equivalent. This only difference being the difference in size.

Your problem is that you're using double quotes. A string declared using double quotes always includes a terminating null character, so a quoted character is implicitly a charactrer array, not a single character. Use single quotes.

This compiles cleanly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Example with:
// character array
#include <iostream>
using namespace std;
int main ()
{
  char letters[5];
  char * p;

  p = letters;  *p = 'A';
  p++;  *p = 'B';
  p = &letters[2];  *p = 'C';
  p = letters + 3;  *p = 'D';
  p = letters;  *(p+4) = 'E';
  for (int n=0; n<5; n++)
    cout << letters[n] << ", ";
  cout << endl;
  return 0;
}


Replace this line
p = letters; *p = "A";

by
p = letters; *p = 'A';

The reason is that concept of array is that one , the first instruction
p = letters;
can be replaced by
p = &letters[0];
the second instruction
*p = 'A'
can be replaced by
p[0] = 'A';
' ' automatically means a char value.
" " means a const char array since it has been defined as constant value.

Note : a pointer size usually is 4 bytes , an integer 4 bytes which could have confused you
a char 1 byte , char * -> pointer -> 4 bytes

It also depends but these are standards value in 32 bits architectures.
Topic archived. No new replies allowed.