Segmentation error with sizeof as row size

I am writing a small program to order a matrix of strings. In the ordination algorithm, I use this function to replace two lines, but in the same cases, the program is split into Segmentation Fault Error. I realized this because of how I initialized temp string, but I did not understand why.

void stringSwap(char*string1,char*string2)
{   const int dim=sizeof(string1);
    char temp[dim];
    strcpy(temp,string1);
    strcpy(string1,string2);
    strcpy(string2,temp);
}

Can someone explain to me why he is giving this error? And is there any other way to do this correctly without using dynamic allocation, which I don't really know? Thank you very much!

+3
source share
4 answers

sizeof(string1) - 4 or 8 bytes, depending on your system.

Use instead strlen(string1)+1.

+3
source

string1 - ( , ), sizeof ( , 4 32- , 8 64- ).

sizeof .

+3

This statement

const int dim=sizeof(string1);

will return sizeof a pointer to char, which sizeof( char * ). Usually it is 4 or 8 bytes depending on the platform on which you run your program.

I think that both lines should have the same size (they may have different actual lengths, but the sizes should be equal), and you should pass this size to the function, or this exchange function does not make sense.

+1
source

to try:

void stringSwap(char*string1,char*string2)
{   
    char temp[strlen(string1)+1];
    strcpy(temp,string1);
    strcpy(string1,string2);
    strcpy(string2,temp);
}
0
source

All Articles