Char and strcpy in C

后端 未结 5 1609
耶瑟儿~
耶瑟儿~ 2021-01-29 14:48

I came across a part of question in which, I am getting an output, but I need a explanation why it is true and does work?

char arr[4]; 
strcpy(arr,\"This is a li         


        
5条回答
  •  無奈伤痛
    2021-01-29 15:22

    your code will always work as long as the printf is placed just after strcpy. But it is wrong coding Try following and it won't work int j; char arr[4]; int i; strcpy(arr,"This is a link"); i=0; j=0; printf("%s",arr); To understand why it is so you must understand the idea of stack. All local variables are allocated on stack. Hence in your code, program control has allocated 4 bytes for "arr" and when you copy a string which is larger than 4 bytes then you are overwriting/corrupting some other memory. But as you accessed "arr" just after strcpy hence the area you have overwritten which may belong to some other variables still not updated by program that's why your printf works fine. But as I suggested in example code where other variables are updated which fall into the memory region you have overwritten, you won't get correct (? or more appropriate is desired) output Your code is working also because stack grows downwards if it would have been other way then also you had not get desired output

提交回复
热议问题