02 WIndows编程——危险的sizeof

C语言中,对 sizeof() 的处理都是在编译阶段进行。

下面代码,注意可变参数是怎么使用的

#include<Windows.h>
#include<stdio.h>

int MessageBoxPrint(char *szFormat, ...);
int fun(char ch[]);

int WinMain(HINSTANCE hInst, HINSTANCE tmp, LPSTR strCmd, int nShow)
{
    char str[1024];
    MessageBoxPrint("%p", hInst);
    MessageBoxPrint("ch=%d", fun(str));
    return 0;
}

int MessageBoxPrint(char *szFormat, ...)
{
    char buf[1024];
    va_list va;
    va_start(va, szFormat);
    vsnprintf(buf, sizeof(buf), szFormat, va);
    va_end(va);
    return MessageBox(NULL,buf,"printf",MB_OK);
}

int fun(char ch[])
{
    return sizeof(ch);
}
View Code

sizeof在fun函数种计算的是指针ch的长度,32位OS下恒为4

sizeof计算字符串含要看在什么位置,写完代码时很难预估风险,最好使用strlen

修改如下

#include<Windows.h>
#include<stdio.h>

int MessageBoxPrint(char *szFormat, ...);
int fun(char ch[]);

int WinMain(HINSTANCE hInst, HINSTANCE tmp, LPSTR strCmd, int nShow)
{
    char str[1024];
    MessageBoxPrint("%p", hInst);
    MessageBoxPrint("ch=%d", fun(str));
    return 0;
}

int MessageBoxPrint(char *szFormat, ...)
{
    char buf[1024];
    va_list va;
    va_start(va, szFormat);
    vsnprintf(buf, sizeof(buf), szFormat, va);
    va_end(va);
    return MessageBox(NULL,buf,"printf",MB_OK);
}

int fun(char ch[])
{
    return strlen(ch);
}
View Code

这时还有个问题,由于WinMain里面str没有初始化,strlen计算长度的时候,长度是未知的。因为他要一直找到才结束,所以strlen的时候长度可能大于1024,可能等于1024,也可能小于1024。

strlen()求的是长度,针对的对象是字符串,而sizeof()求的是大小,针对的是类型,首先要明确的一个概念是,strlen()是函数,而sizeof()表面看起来是函数,其本质是关键字。

printf函数原型

extern int printf(const char *format,...);

vsnprintf()函数 & vfprintf()函数

vsnprintf函数
头文件:#include  <stdarg.h>
函数原型:int vsnprintf(char *str, size_t size, const char *format, va_list ap);
函数说明:将可变参数格式化输出到一个字符数组
参数:str输出到的数组,size指定大小,防止越界,format格式化参数,ap可变参数列表函数用法
 
vfprintf()函数
头文件:#include  <stdarg.h>
函数原型: int vfprintf(FILE *stream, const char *format, va_list arg);
函数说明:fprintf()会根据参数format字符串来转换并格式化数据,然后将结果输出到参数stream指定的文件中,直到出现字符串结束(‘’)为止。
原文地址:https://www.cnblogs.com/kelamoyujuzhen/p/9298249.html