Pelles C forum
C language => Expert questions => Topic started by: EdPellesC99 on July 05, 2010, 07:49:50 PM
-
Hi,
This code works#include <stdio.h>
int main()
{
char buff[50];
int ret, a = 34;
ret = sprintf(buff, "%d",a);
printf ("\n\nbuf as text is: %s and the buffer has %d characters.\n\n",buff,ret);
return 0;
}
Can someone explain to me why the following compiles, but does not run:
#include <stdio.h>
int main()
{
char buff[50];
int ret, a = 34;
ret = sprintf(buff, "%d",a);
printf ("\n\nbuf as text is: %s and the buffer has %d characters.\n\n",buff[0],ret);
return 0;
}
On a sidenote: I continue, hopefully not forever, to have problems with the concept of pointers.
Anyway, on the last code block, doesn't integer "a" get written to the first cell of buff as text?
Thanks in advance for all help,
... Ed
-
Use &buff[0] for pointer to string
-
Great Timo,
Thanks very much, I do not think I would ever have figured that one out. Sometimes you just get stuck, and you stay there no matter how many places you look for answers, and no matter how many times you try things in new ways.
Very nice, I am stunned at the moment, and might ask a question in a day or two after my brain is capable.
Tx much, Ed
-
Example to use sprintf and array of char
#include <stdio.h>
int main(int argc, char **argv)
{
int pos;
char buff[100];
pos = 0;
for (int i=0; i<=10; i++) {
pos += sprintf(&buff[pos], "i=%d\n", i);
}
printf(buff);
return 0;
}
Tutorial for pointers:
http://home.netcom.com/~tjensen/ptr/pointers.htm (http://home.netcom.com/~tjensen/ptr/pointers.htm)
-
Tx Timo,
For the info, and the link. I will be reading, .......it looks like some great info.
Tx again, and I like that color syntax in the post ! :) :)
.....Ed