How can I add more values to a char array using pointers? (Beginner)

#include <iostream>
using namespace std;


char a[50];

void addSpace (){
cin.getline (a,50);
const char * x = a;
while (x != a + sizeof(a)) {
cout << *x << " ";
++x;
}
}

int main() {
addSpace();
cout << endl;
return 0;
}

I'm quite a newbie. So I made this code last night which I'm really proud of, but it's only to read out. It's not really modifying the values of the array. Is it possible to make a function using pointers, that for example let's say we enter the word "Hello!" to modify it in such a way that a[0]='H', a[1]=' ', a[2]='e', a[3]=' ' a[4]='l' a[5]=' ' ... and so on ? Using pointers! Thank you!

Edit: I think I actually made it but it requires another char array. Is there a way to use only a without b?

    #include <iostream>
using namespace std;


char a[50];
char b[sizeof(a)*2];

void addSpace (){
cin.getline (a,50);
char * x = a;
char * y = b;
while (x != a + sizeof(a)) {
*y++=*x++;
*y++=' ';
}
cout << b;
}

int main() {
addSpace();
cout << endl;
return 0;
}
728x90

0 Answers How can I add more values to a char array using pointers? (Beginner)