问题描述
我还在学习,因此可以原谅另一个菜鸟问题.
我会将代码简化到让我感到悲伤的地方.
我要做的就是得到一个字符串,在其末尾加一个数字,然后显示出来.字符串按计划到达屏幕,但是在函数末尾出现堆栈损坏,因为它将控制权返回给WndProc.
I''m still learning so forgive another noob problem.
I''ll abreviate the code to around the area that has given me grief.
All I''m trying to do is get a string, slap a number onto the end of it, then display it. The string arrives on the screen just as planned, but I get the Stack Corruption at the end of the function as it returns control to WndProc.
#include <windows.h>
#include <stdlib.h>
void FailingFunction(HWND hwnd)
{
HDC hdc = GetDC(hwnd);
RECT TextRect1;
int aNumber = 10;
wchar_T ident[] = L"A string";
wchar_T Out[50];
TextRect1.top = 15;
TextRect1.left = 15;
TextRect1.bottom = 100;
TextRect1.right = 100;
PrepTextOut(ident, Out, aNumber);
DrawText(hdc, Out, -1, &TextRect1, DT_SINGLELINE | DT_CENTER | DT_VCENTER)
ReleaseDC(hwnd,hdc);
}
void PrepTextOut(wchar_t* str, wchar_t* dest, int value)
{
wchar_t cNum[10]; //Wide character array to hold integer
size_t cNumSize = 10; //size of ''wchar_t cNum''
size_t destSize = wcslen(dest); //size of dest wide character array
_itow_s(value, cNum, cNumSize, 10); //Convert cNum integer to wchar_t
wcscpy_s(dest, destSize, str); //Copy str into dest
wcscat_s(dest, destSize, cNum); //Contracate cNum onto dest
}</stdlib.h></windows.h>
我需要执行此步骤数十次,并希望缩短代码.我已经包括了所有使其运行的必需品.我的测试整数是1.测试字符串是"Strength".
我们非常感谢您的帮助.
I need to do this step dozens of times and was looking to shorten the code. I''ve included all of the necessities to make it run. My test integer was 1. Test string was ''Strength''.
Any help is greatly appreciated.
推荐答案
//void PrepTextOut(wchar_t* str, wchar_t* dest, int value)
void PrepTextOut(wchar_t* str, wchar_t* dest, size_t destSize, int value)
// needs one more parameter for destsize
{
//wchar_t cNum[10]; //Wide character array to hold integer
// 10 is not enough (together with terminator null and posible minus sign,
// should be at least 12 for 32 bit integers)
wchar_t cNum[16]; // guarantee
// size_t cNumSize = 10; // size of ''wchar_t cNum''
size_t cNumSize = sizeof(cNum) / sizeof(cNum[0]);
// size_t destSize = wcslen(dest); //size of dest wide character array
// dest may points uninitalized buffer so you shouldn''t do above
_itow_s(value, cNum, cNumSize, 10); //Convert cNum integer to wchar_t
wcscpy_s(dest, destSize, str); //Copy str into dest
wcscat_s(dest, destSize, cNum); //Contracate cNum onto dest
}
这篇关于变量周围的另一个“堆栈已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!