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