1

My question is about efficiency of the swap char pointer algorithm.

Why either of the commented lines causes my complier to throw error?

The same logic works for swapping b with temp, but the same logic causes error while repeating in the same function for the temp and a?

Thank you all.

#include <iostream>
void sawp ( char *a, char *b, int l)
{
    char * prtA = a;
    char * prtB = b;
    char *temp = (char *)calloc(l, sizeof(char));

    while(*(char*)b)
    {        
        *(char*)temp= *(char*)b;
        // *(char*)b  = *(char*)a;
        // *(char*)a = *(char*)temp;

        std::cout<<*(char*)temp<<std::endl;
        b++;
        temp++;
        a++;    
    }

}

int main()

{
    char *a="Name";
    char *b="Lastname";
    sawp (a,b,sizeof(b));
    return 0;

}
  • 1
    Side note #1: Those `(char*)` castings are completely redundant - you are casting a `char*` to a `char*`. Side note #2: You've misspelled `swap` as `sawp`. Side note #3: You're not doing anything with `prtA` and `prtB`. Side note #4: You've misspelled "compiler" as "complier". All these side notes are just to tell you that you should put a little effort before posting a question here (that is, if you expect others to put an effort answering it). Important note #1: It's not the compiler that "throws an error", because it is not a compilation error - it's a runtime error!!! – barak manos Dec 10 '14 at 18:35

4 Answers4

2

Modifying string literals results in undefined behavior. It might cause a crash. String literals are read only and hence they can't be modified.

So

*b = *a;

is an error.

If you want to modify your string then they should have read and write access. So

char a[10] = "name1";
char b[10] = "name2";

Then you can have

*b = *a; /* In your sawp() function */
Gopi
  • 19,784
  • 4
  • 24
  • 36
2

Writing char *a="Name" the compiler will treat the "Name" string as a constant string and will place it in the rom memory section. The rom memory section is a read only section and the code has no permission to change it in run time, so it will rise a segmentation fault when you try to change it.

0

Did you took a look at this entry? Swapping pointers in C (char, int)

In the end, there's an explanation on how to swap chars. Maybe it fits you.

Community
  • 1
  • 1
pedrop
  • 134
  • 1
  • 7
0

To avoid the issue with literals as posted by Gopi, you could use character arrays instead of pointers in main, and make sure they are the same size, for example:

char a[10] = {'N','a','m','e',0,0,0,0,0,0};
char b[10] = {'L','a','s','t','n','a','m','e',0,0};
/* ... */
    sawp(a, b, sizeof(b));

or if you still wanted to use pointers, you could use malloc() (assuming this is C and not C++) to allocate space for the strings, and then copy literals into the strings you allocated.

rcgldr
  • 27,407
  • 3
  • 36
  • 61