Pelles C forum

C language => Expert questions => Topic started by: EdPellesC99 on July 05, 2010, 07:49:50 PM

Title: Need sprintf to format an integer to text, but confused with fundamentals
Post by: EdPellesC99 on July 05, 2010, 07:49:50 PM

   Hi,

   This code works
Code: [Select]
#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:

Code: [Select]
#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

Title: Re: Need sprintf to format an integer to text, but confused with fundamentals
Post by: TimoVJL on July 05, 2010, 09:23:29 PM
Use &buff[0] for pointer to string
Title: Re: Need sprintf to format an integer to text, but confused with fundamentals
Post by: EdPellesC99 on July 05, 2010, 10:37:41 PM
   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
Title: Re: Need sprintf to format an integer to text, but confused with fundamentals
Post by: TimoVJL on July 06, 2010, 07:57:47 AM
Example to use sprintf and array of char
Quote
#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)
Title: Re: Need sprintf to format an integer to text, but confused with fundamentals
Post by: EdPellesC99 on July 06, 2010, 06:05:10 PM
 
  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