snprintf事例

来源:互联网 发布:订票系统的数据设计 编辑:程序博客网 时间:2024/04/30 08:24

sizeof Operator

sizeof expression

The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t.

The expression is either an identifier or a type-cast expression (a type specifier enclosed in parentheses).sizeof后面跟的表达式(expression)既可以是标志符,也可以是类型转换的表达式(类型的说明包含在))

When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.

 

strlen

Get the length of a string.

Routine Required Header

strlen <string.h>

size_t strlen( const char *string );

Parameter

stringNull-terminated string

Libraries

All versions of the C run-time libraries.

Return Value

Each of these functions returns the number of characters in string, excluding the terminal NULL. No return value is reserved to indicate an error.

 

Remarks

Each of these functions returns the number of characters in string, not including the terminating null character. wcslen is a wide-character version of strlen; the argument of

wcslen is a wide-character string. wcslen and strlen behave identically otherwise.


snprintf


  int snprintf(char *str, size_t size, const char *format, ...);
  将可变个参数(...)按照format格式化成字符串,然后将其复制到str中
  (1) 如果格式化后的字符串长度 < size,则将此字符串全部复制到str中,并给其后添加一个字符串结束符('\0');
  (2) 如果格式化后的字符串长度 >= size,则只将其中的(size-1)个字符复制到str中,并给其后添加一个字符串结束符('\0')
  函数返回值:若成功则返回欲写入的字符串长度,若出错则返回负值。


例:

char str1[3] = "123";

char str2[3] = "";

snprintf(str2, sizeof(str1), "%s", str1);

printf("str2 = %s\n", str2);

例子有问题,看家自己分析。面试的时候遇到的。



原创粉丝点击