I'm having trouble manipulating strings on C.
I wrote this code to concatenate various values and run a python scrip from my C program.
void python_print(float circle_1[3],float circle_2[3],float circle_3[3],
float x, float y){
char run_this[200]="python3 beacons.py ";
char circle_str_1[30],circle_str_2[30],circle_str_3[30],
x_position[10],y_position[10];
float *c1=&circle_1[0];
float *c2=&circle_2[0];
float *c3=&circle_3[0];
sprintf(circle_str_1," %f %f %f", *c1,*(c1+1),*(c1+2));
sprintf(circle_str_2," %f %f %f", *c2,*(c2+1),*(c2+2));
sprintf(circle_str_3," %f %f %f", *c3,*(c3+1),*(c3+2));
sprintf(x_position," %f",x);
sprintf(y_position," %f",y);
puts(circle_str_1);
puts(circle_str_2);
puts(circle_str_3);
puts(x_position);
puts(y_position);
puts(run_this);
strcat(run_this, circle_str_1);
strcat(run_this, circle_str_2);
strcat(run_this, circle_str_3);
strcat(run_this, x_position);
strcat(run_this, y_position);
system(run_this);
}
For some reason circle_str_1
prints nothing, and the string I got a the end does not contain circle_str_1
and doubles the values for y_position.
circle_1={0.0,0.0,9.107}
circle_2={16.0,0.0,22.121}
circle_1={0.0,16.0,24.260}
y=-7.800317
x=-4.700037
Buffers are too small.
sprintf(x_position," %f",x);
needs at least a buffer of 11. Printing into x_position[10]
leads to undefined behavior .
1: Consider using snprintf()
to avoid buffer overflow. 2: use larger buffers. 3: Avoid "%f"
format as it can quickly lead to outputs of hundreds of characters. Consider "%g"
// char x_position[10],
// sprintf(x_position," %f",x);
char x_position[20];
int len = snprintf(x_position, sizeof x_position, " %g", x);
if (len < 0 || (unsigned) len >= sizeof x_position) {
puts("Trouble printing");
...
}
Do not use sprintf()
, strcpy()
, strcat()
unless you have absolute certainly that overflow will not occur.
%f v. %g
printf("%%f <%f>\n", -DBL_MAX);
printf("%%g <%g>\n", -DBL_MAX);
Output
%f <-179769313486231570814527423731704356798070565449239578069709514447683386590106403234437238318580897337933920052621128987133479958537240295444402082043505598186819583097828779632178833278408753356733764414284292236482024122876814115690851853178733231033249466834451356736736928870307247739983885979597249860971.039805>
%g <-1.79769e+308>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.