Pointers and arrays

Hi Lads,
I don't understand why on the output I'm missing the last word from the sentence:

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
41
#include <iostream>
#include <new>

using namespace std;
int a,b,c;
char * z;
char * x;
char * v;
void * guru[6];
char * papa;
int main(){
    z = new char;
    x = new char;
    v = new char;
  cout << "Give me first word: ";
  cin >> z;
  cout << "Give me second word: ";
  cin >> x;
  cout << "Give me third word: ";
  cin >> v;
  guru[0]=z;
  guru[1]=x;
  guru[2]=v;
  cout << "Your sentence is: ";
  papa = (char*)guru[0];
  cout << papa;
  cout << " ";
  papa = (char*)guru[1];
  cout << papa;
  cout << " ";
  papa = (char*)guru[2];
  cout << *papa;
  cout << " !";
    cin >> c;
 return 0;   
}




Last edited on
You have many problems with this code.

z = new char;

This allocates space for exactly 1 char....

cin >> z;

... but you are expecting the user to enter a word (multiple chars).

Lines 21 on I don't know what you are trying to do. If z, x, and v were allocated correctly to hold words (strings), then you could simply output z, x, and v separated by spaces. There is no need to store them into a void* array (guru) and output from there.

The output problem is caused by line 32, you don't need the * there,
cout << papa; will display the entire C string
cout << *papa; will display only the first character of it
What I'm trying to do is build an array that holds pointers to strings(words). This can give me a possibility to operate on them during the runtime later on in some bigger program . :-)
YEAH, THX Bazzy :D
Ok, in that case, any of the following declarations will provide you want you want, just in different ways.

1
2
3
4
5
6
7
8
char** dynamicSizedArrayOfCStrings;
char*   fixedSizeArrayOf20CStrings[ 20 ];
string* dynamicSizedArrayofSTLStrings;
string   fixedSizeArrayOf20STLStrings[ 20 ];

vector<string> dynamicSizedSTLVectorOfSTLStrings;
deque<string> ...;
list< string >    ...;


I would not use void* in your case.

I'm pretty new in C++ and I don't understand vector's yet ( I'm in a half way of "C++ Language Tutorial") but I be back in a week time and see what you give me :D thx jsmith
Last edited on
Topic archived. No new replies allowed.