question on char*

experts, how can i copy part of char* to a new variable, cus i need to use that part to make a contrast

char *strings contains abcdefghijkl
char *temp NULL

if i wanna take efgh from strings and put it in temp. what can i do?

i try using this

1
2
3
4
5
6
7
char *temp;
int index = 0;
for(int i = stringStart; i <= stringEnd; i++)
{
   temp[index] = strings[i];
   index++;
}


however, error message is segmentation fault
from the code above it looks like it's probably because temp is NULL, so copying elements from strings would be written to a null pointer. Make temp an array like strings and then you can copy to it as you have in your for loop.
Remember to add the terminating '\0' to your temp string.
Last edited on
In that code you haven't allocated memory for the variable temp. You shouldn't be copying data into the variable before you have allocated memory.

You could do this:
char temp[5];
or a dynamic allocation like so:
char* temp = new char[5];

Note that if you allocate dynamically, you must deallocate when you are done with the memory:
delete [] temp;

As Moooce said, remember than you need to put a null terminator '\0' at the end of a string. In particular, remember to allocate enough space for this character.
Topic archived. No new replies allowed.