什么时候应该使用sizeof(c),什么时候又该用c.size()呢
时间: 2024-05-30 14:12:27 浏览: 41
你可以在以下情况下使用sizeof(c):
1. 数组类型:sizeof(c)将返回整个数组的字节数。
2. 指针类型:sizeof(c)将返回指针类型的字节数。
3. 自定义类型:sizeof(c)将返回自定义类型的字节数。
你可以在以下情况下使用c.size():
1. 字符串类型:c.size()将返回字符串中字符的数量。
2. 容器类型:c.size()将返回容器中元素的数量。
相关问题
c语言sizeof是什么
在 C 语言中,sizeof 是一个运算符,用于计算变量或数据类型的大小,单位是字节。sizeof 运算符的语法如下:
```
sizeof (type)
```
其中,type 可以是一个数据类型(如 int、float、char 等)或一个变量名。sizeof 运算符的返回值是一个整数,表示 type 所占用的字节数。
例如,下面的代码演示了如何使用 sizeof 运算符来计算不同类型的变量所占用的字节数:
```
#include <stdio.h>
int main() {
int a;
float b;
char c;
printf("Size of int: %lu bytes\n", sizeof(a));
printf("Size of float: %lu bytes\n", sizeof(b));
printf("Size of char: %lu bytes\n", sizeof(c));
return 0;
}
```
输出结果如下:
```
Size of int: 4 bytes
Size of float: 4 bytes
Size of char: 1 bytes
```
在这个例子中,我们定义了一个 int 类型的变量 a、一个 float 类型的变量 b 和一个 char 类型的变量 c,然后使用 sizeof 运算符分别计算它们所占用的字节数,并使用 printf 函数输出结果。可以看到,int 和 float 类型的变量都占用了 4 个字节,而 char 类型的变量只占用了 1 个字节。
c语言sizeof用法
在 C 语言中,`sizeof`是一个关键字,用于获取数据类型或变量在内存中所占的字节数。其语法如下:
```c
sizeof(type)
sizeof(expression)
```
其中,`type`是数据类型,可以是基本数据类型、自定义数据类型或指针类型,`expression`是一个表达式或变量名。`sizeof` 运算符返回一个 `size_t` 类型的值,表示数据类型或变量在内存中所占的字节数。
例如,可以使用 `sizeof` 来获取不同类型的大小:
```c
#include <stdio.h>
int main() {
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of double: %zu bytes\n", sizeof(double));
printf("Size of char: %zu bytes\n", sizeof(char));
printf("Size of long: %zu bytes\n", sizeof(long));
printf("Size of short: %zu bytes\n", sizeof(short));
printf("Size of long long: %zu bytes\n", sizeof(long long));
printf("Size of unsigned int: %zu bytes\n", sizeof(unsigned int));
printf("Size of int *: %zu bytes\n", sizeof(int *));
printf("Size of struct: %zu bytes\n", sizeof(struct MyStruct));
return 0;
}
```
输出结果:
```
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 bytes
Size of long: 8 bytes
Size of short: 2 bytes
Size of long long: 8 bytes
Size of unsigned int: 4 bytes
Size of int *: 8 bytes
Size of struct: 24 bytes
```
注意:`sizeof` 返回值的类型是 `size_t`,需要用 `%zu` 输出格式符打印。
阅读全文
相关推荐















