c - Why is strcpy(strerror(errno),"Hello") not copying "Hello",but {ptr=strerror(errno);strcpy(ptr,"Hello");} does? -


please explain what's going on in following program.

i checked out addresses returned strerror(errno) @ beginning , end of program , confirms returns same address each time.then once sure of this,in first case proceeded assign same address ptr , copy string "hello" using strcpy().in case ii,i tried copy "hello" directly address returned strerror(errno).i had odd findings.i'll appreciate if explain following:

in case one,i copied "hello" ptr , successful in subsequent printf(),ptr prints hello.but then, when passed strerror(errno) instead of ptr printf(),it prints old error message.how possible ptr points 1 message strerror(errno) points message when both addresses same?i verified both addresses same , expect copying "hello" ptr should same copying return of strerror(errno).to doubly check discrepancy,then tried copy "hello" directly strerror(errno) doesn't work time , prints same old error string.but surprising thing is,at point too, verified again addresses ptr , strerror(errno) indeed same along!! how possible?if same how pointing different strings?one "hello" , other old custom error message?

please explain reason behind this.

#include <stdio.h> #include <string.h> #include <errno.h>  int main () { char *ptr;   file * fp;   fp = fopen ("missingfile.txt","r");   if (fp == null)     printf ("%s\n",strerror(errno));     printf("\n%p",strerror(errno));  //initial address      //case1:     ptr=strerror(errno);     strcpy(ptr,"hello");     printf("\n%s",ptr);  //prints hello     printf("\n%s",strerror(errno)); //still prints old message       //case2:     strcpy(strerror(errno),"hello"); //doesn't copy hello there     printf("\n%s",strerror(errno)); //still prints old message       printf("\n%p",strerror(errno)); //address same @ start     printf("\n%p",ptr);  //same address above statement     return 0; } 

output

no such file or directory  00032508 hello no such file or directory no such file or directory 00032508 00032508 

in

//case2: strcpy(strerror(errno),"hello"); //doesn't copy hello there printf("\n%s",strerror(errno)); 

your second call strerror in printf overwrites copied.

this bad-form, way around.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -