你好,我在使用 sprintf
时遇到了一个奇怪的问题。这是我的代码:
void draw_number(int number,int height,int xpos,int ypos){
char string_buffer[5]; //5000 is the maximum score, hence 4 characters plus null character equals 5
printf("Number - %i\n",number);
sprintf(string_buffer,"%i",number); //Get string
printf("String - %s\n",string_buffer);
int y_down = ypos + height;
for (int x = 0; x < 5; x++) {
char character = string_buffer[x];
if(character == NULL){ //Blank characters occur at the end of the number from spintf. Testing with NULL works
break;
}
int x_left = xpos+height*x;
int x_right = x_left+height;
GLfloat vertices[] = {x_left,ypos,x_right,ypos,x_left,y_down,x_right,y_down};
rectangle2d(vertices, number_textures[atoi(strcat(&character,"\0"))], full_texture_texcoords);
}
}
通过那里的 printf
调用,数字打印成功,数字按预期绘制。当我拿走它们时,我当然无法查看输出并进行比较,但数字无法正确呈现。我假设 sprintf
以某种方式中断。
NSLog
也会发生这种情况。在程序中的任何位置添加 NSLog
可以破坏或修复该功能。
到底是怎么回事?
这是将 Objective-C 与 iOS 4 SDK 结合使用。
感谢您的任何回答。
这段代码肯定很奇怪
char character = string_buffer[x];
...
... strcat(&character,"\0") ...
最初我在想,这取决于何时堆栈上恰好有一个 NUL 终止符,这会破坏一些内存,并可能导致您的问题。但是,由于您要附加空字符串,我认为它不会产生任何影响。
也许堆栈的内容实际上包含 atoi
正在解释的数字?无论哪种方式,我建议您解决这个问题,看看它是否能解决您的问题。
至于如何修复它,Georg Fritzsche 先于我。
我是一名优秀的程序员,十分优秀!