0

你好我有一个奇怪的问题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' 都可以破坏或修复该功能。

到底是怎么回事?

这是在 iOS 4 SDK 中使用 Objective-C。

谢谢你的任何回答。

4

4 回答 4

4

那么这段代码肯定很奇怪

char character = string_buffer[x]; 
...
... strcat(&character,"\0") ...

最初我在想,根据堆栈上碰巧有 NUL 终止符的时间,这会破坏一些内存,并可能导致您的问题。但是,由于您要附加空字符串,我认为它不会产生任何影响。

也许堆栈的内容实际上包含atoi正在解释的数字?无论哪种方式,我建议您修复它,看看它是否解决了您的问题。

至于如何修复它,Georg Fritzsche 打败了我。

于 2010-09-01T13:38:36.763 回答
2

随着strcat(&character,"\0")您尝试将单个字符用作字符数组。这可能会导致atoi()返回与您期望的完全不同的值(因为您没有空终止)或只是崩溃。

要修复原始方法,您可以使用正确的以零结尾的字符串:

char number[] = { string_buffer[x], '\0' };
// ...
... number_textures[atoi(number)] ...

But even easier would be to simply use the following:

... number_textures[character - '0'] ...
于 2010-09-01T13:44:32.477 回答
1

Don't use NULL to compare against a character, use '\0' since it's a character you're looking for. Also, your code comment sounds surprised, of course a '\0' will occur at the end of the string, that is how C terminates strings.

If your number is ever larger than 9999, you will have a buffer overflow which can cause unpredicable effects.

于 2010-09-01T13:53:43.327 回答
1

When you have that kind of problem, instantly think stack or heap corruption. You should dynamically allocate your buffer with enough size- having it as a fixed size is BEGGING for this kind of trouble. Because you don't check that the number is within the max- if you ever had another bug that caused it to be above the max, you'd get this problem here.

于 2010-09-01T13:53:49.130 回答