*char to char[]

Hello everyone, this is my first time on these boards.

I recently started learning C++ and pointers are driving me crazy.

I have created a function to which 2 parameters are sent:
int MyFunction(char *p1, char p2)
Now the first parameter is a char pointer and I need to extract specific characters from the pointer to an array char[n].

How am I supposed to do this? All string functions seem to work the other way ... converting char[] to char*.

Best regards,
-Vent
Last edited on
int MyFunction(char *p1, char p2)
Now the first parameter is a char reference


Looks like a char pointer to me, which is completely different.

My bad, yeah I meant pointer.
If you have a pointer to a char, and you want to copy the char it is pointing to into a position in an array, try this:

destinationArray[positionToWriteTo] = *charPointer;



I have a pointer to string.
char *MyPointer = "my pointer";
Does that work OK? Because the MyPointer variable will be holding an address that should be read-only. Don't you have to do const char *MyPointer = "my pointer";?
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
#include<iostream>

int main()
{

  char *somePointer = "my pointer";

  char arrayOfChars[10];

  arrayOfChars[9] = '\0'; // Put a terminator on the end

  std::cout << somePointer << std::endl;
  std::cout << arrayOfChars << std::endl;

  for (int i=0; i<9; i++)
    {
      arrayOfChars[i]='X';
    }

  std::cout <<  arrayOfChars << std::endl;

  

  arrayOfChars[0] = *somePointer;
std::cout <<  arrayOfChars << std::endl;

  arrayOfChars[3] = *somePointer;
 std::cout <<  arrayOfChars << std::endl;

 somePointer = somePointer + 5;

 arrayOfChars[7] = *somePointer;
std::cout <<  arrayOfChars << std::endl;
 return 0;
}


This code shows copying various letters of the C-style string into a different c-style string. Hoepfully this demonstrates what you're looking for.

I have a pointer to string.
char *MyPointer = "my pointer";


What you have there is a pointer to the first element of an array of characters. You can change the value of the pointer, and that will move the pointer along in memory, and you can dereference the pointer, which will give you whatever character is it currently pointing at.
Why not just use std::strings for doing things with strings? (Rhyme unintended)
http://cplusplus.com/reference/string/string/

-Albatross
Last edited on
+1 @ Albatross
Thanks for replies and examples!
Topic archived. No new replies allowed.