[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: small c problem



Michael Beattie a écrit:
> 
> The following problem will help me finish v0.1 of my wizard radio control
> program which I will ITP and upload soon..
> 
> <prepared for flames>
> 
> I know its the wrong place to ask, but its really easy, and I feel stupid
> asking in a newsgroup....
> 
> string with value "number:"
> 
> integer with value "444"
> 
> I want the string to then have the value "number:444"
> 
> this is the actual C code:  (slightly snipped)
> 
>    int freq_num;
>    double freq;
>    char *rad_cmd;
> 
>    freq = atof(optarg);   // optarg is "98.2"
> 
>    freq_num = (int) ((freq - 76) / 0.05);   // gives 444
> 
>    rad_cmd = "number:";
> 
>    What now?  i.e.  rad_cmd+freq_num to give rad_cmd = "number:444"
>    strcat()?
> 

hmmm the better way to do this is :

	#include <stdlib.h>
	#include <stdio.h>

        ...
	
	char *rad_cmd;
          
	rad_cmd=(char *)malloc(a big enough string size+1 for the \0);
	freq_num = (int) ((freq - 76) / 0.05);   // gives 444
	sprintf(rad_cmd,"number : %03d",freq_num);

	...

	free(rad_cmd);

	....

You can write, rad_cmd=(char *)malloc((a big enough string size+1 for
the \0)*sizeof(char)); for a more secure allocation but I do not know
which platforms (if any) have a char wider than 1 byte...

	You can to this in a less dynamic way :

	#include <stdio.h>

	...


	char rad_cmd[a big enough string size+1 for the \0];

	freq_num = (int) ((freq - 76) / 0.05);   // gives 444
	sprintf(rad_cmd,"number : %03d",freq_num);

	...

	No more malloc/free required.


regards,

	Adrien	


-- 
------
Adrien Dessemond
Eleve ingenieur 

Institut Mediterraneen d'Etudes et Recherches en Informatique, IA,
Robotique - Perpignan (FRANCE)

http://www.imerir.asso.fr - Mortal Kontakt : dessemond@imerir.asso.fr

"Going on means going far. Going far means returning.


Reply to: