Hey everyone ! I was trying to make a program that sorts various strings. I succeeded but when i tried with pointers I failed.
See please let me know how do make a character pointer move from one row to the other while pointing at ... suppose a 20X20 string.
So if I understand correctly, you have 20 strings, each with 20 characters? If you want to replace each string with another, and YOU'RE SURE that they all have the same length, then you have to do it letter by letter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
constint length = 20;
char* str1 = newchar[length];
char* str2 = newchar[length];
char tempChar; //single character to store buffer characters.
str1 = "abcdefghijklmnopqrst";
str2 = "hellohellohellohello";
for(int i = 0; i < length; i++)
{
tempChar = str1[i];
str1[i] = str2[i];
str2[i] = tempChar;
}
//now here you have str1 and str2 swapped
Not really... it's not faster. It's just the same! you're using a built in function. The problem is that the guy's defined the length and hasn't used null terminated strings. So we can't guarantee that strcpy would work.
That is why i got confused, because you missed the "new" operator.
And, you should use const char * (as clanmjc said).
And anyways, it will result in a Memory Leak.
Why?
Because you first assign to the var mystr1 (length) characters.
Then you again assign and overwrite the var mystr1 with a const char * variable.
What you probably meant is strcpy.
I think anyways we are missing the op's question.
Personally i didn't understand it, so if our op could "clean up" his question, I will be easily able to help him.
(What I mean is, You cannot "switch" constant pointers. What the op asked is to switch pointers, so, are you using 'new' for declaring your pointers?)