buf is a name of an array that is statically defined in the code.
In other words, it is assigned to the stack, you can't change the value of buf as you doing in the code.
For you code to work correctly as you wrote it here, you have to define buf as a char pointer then allocate the storage for it using malloc function. By this, buf will be allocated in the heap and you will avoid this error.
It works with sprintf because you copy to the contents of buf not modifying buf itself as your original code was doing.
How to use malloc?
I prefer to refer to opengroup.org when I have questions about functions and their usage"http://www.opengroup.org/onlinepubs/009695399/functions/malloc.html"
Thanks a lofor your immidiate reply. I tried doing this. First it gave me error malloc function missing Then I added malloc.c file from hitech picc folder to my source file list now it's giving me error :-
Code:
Error [480] ; . function signatures do not match: _malloc (malloc.obj): 0x1079/0x42
Error [499] ; . undefined symbol:
_sbrk (malloc.obj)
Buf is an array variable. When using buf without an index, it's equivalent to a constant pointer, that holds the address of
the array, but it can't be changed. You need to use a real pointer variable. Also you must add a string terminator to
print the string.