DBS
DBS

Reputation: 131

what is the pointer error in this code?

I am trying to understand pointers and here is a program in K&R that I am trying to implement. The program is strcpy with code from KR.

/*strcpy: copy t to s; pointer version 3*/
void strcpy(char *s, char *t){

while(*s++ = *t++)     
    ;              
}

So to implement this program, I add

#include<stdio.h>
int main(){

    char *s="abc", *t="ABC" ;

    strcpy(s,t);
    printf("%s\n",t);

    printf("%s\n", s);
    return 0;
}

However I am getting segmentation error when I run it. I am sure I am missing something but not quite sure what.

Thanks!

Upvotes: 1

Views: 130

Answers (2)

Yu Hao
Yu Hao

Reputation: 122493

char *s="abc", *t="ABC" ;

string literals are not modifiable, however, a char array can be modified, so change it to :

char s[] ="abc", *t="ABC" ;

Upvotes: 8

Joni
Joni

Reputation: 111389

Literal string values are stored in a read-only memory page; they cannot be modified.

Upvotes: 7

Related Questions