-1
#include<stdio.h>
int main(void)
{
    char str1[10]="Versace";
    int length(char *p);
    char* reverse(char *p);

    printf("Length of the array is %d\n",length("Versace")); 

    printf("Reversed string %s",reverse("Versace"));
}
int length(char*p)
{
     int i;
     for(i=0;*(p+i)!='\0';i++);
     return i;
}
char* reverse(char *p)
{
     int i,l;
     char temp;
     for(l=0;*(p+l)!='\0';l++);
     
     for (i=0;i<(l/2);i++)
     {
           temp=*(p+i);
           *(p+i)=*(p+l-1-i);
           *(p+l-1-i)=temp;
    }
     return(p);

}

I have written a code to find the length of a string and to reverse a string.For this purpose I've made 2 functions reverse and length. But, why does this code show error? The code works fine if I use str1 as parameter in reverse function in the second printf.

Aish97
  • 7
  • 1

1 Answers1

1

The compiler warning -Wwrite-strings offers a clue.

test.c:9:49: warning: passing 'const char [8]' to parameter of type 'char *' discards qualifiers
      [-Wincompatible-pointer-types-discards-qualifiers]
    printf("Length of the array is %d\n",length("Versace"));

"Versace" is stored in the executable itself which is mapped to appear to be read-only memory. If you look at your executable in an editor, you will see Versace among the noise. It is read-only and you're trying to modify it.

If we make the change the warning suggests and have reverse take a const char * we get a compiler error because you can't change a constant.

test.c:22:16: error: read-only variable is not assignable
         *(p+i)=*(p+l-1-i);
         ~~~~~~^
test.c:23:20: error: read-only variable is not assignable
         *(p+l-1-i)=temp;

char str1[]="Versace"; also stores "Versace" in the executable, but it then copies it into real memory which can be modified.

Schwern
  • 153,029
  • 25
  • 195
  • 336