C语言 sizeof, size_t, strlen

文章详细介绍了C语言中的sizeof运算符用于计算类型或结构体所占内存大小,例如在结构体中,定义chararr[]与char*arr的区别。size_t类型用于存储大小且具有平台无关性。同时,文章对比了sizeof和strlen的区别,前者计算内存分配大小,后者计算字符串长度直到遇到为止。
摘要由CSDN通过智能技术生成

C语言 sizeof, size_t, strlen

一. sizeof

返回一个结构体或者类型所占的内存字节数

1.1 返回结构体长度

这里我编写了2个结构体,区别在于数组问题

#include <stdio.h>

struct test{
	int length;
	int space;
	char arr[];
};
struct _test{
	int length;
	int space;
	char *arr;
};
int main(){
	printf("%d\n",sizeof(struct test));
	printf("%d\n",sizeof(struct _test));
	return 0;
}

编译c文件,查看结果

[root@localhost second-six]# gcc demo_sizeof.c
[root@localhost second-six]# ./a.out 
8
16

从这里我们可以看出定义char arr[]和char *p,输出的结果不同

  1. char arr[],初始化为0字节,需要到时在堆内存赋值长度,拿一个redis2.8.14源码示例,sds.c文件

    可变数组,在编译期生成,没有编译期不生成,必须动态分配

sds sdsnewlen(const void *init, size_t initlen) {
    struct sdshdr *sh;

    if (init) {
   		// 初始化内存
        sh = zmalloc(sizeof(struct sdshdr)+initlen+1); 
    } else {
        // 初始化内存
        sh = zcalloc(sizeof(struct sdshdr)+initlen+1);
    }
    if (sh == NULL) return NULL;
    sh->len = initlen;
    sh->free = 0;
    if (initlen && init)
        memcpy(sh->buf, init, initlen);
    sh->buf[initlen] = '\0';
    return (char*)sh->buf;
}

// 结构体
struct sdshdr {
    unsigned int len;
    unsigned int free;
    char buf[];
};
  1. char *arr,可通过汇编看出

    默认赋值16,而char *arr相当于初始化机器的位数,如机器是64bit,则初始化8byte

[root@localhost second-six]# gcc -S -fno-asynchronous-unwind-tables demo_sizeof.c
[root@localhost second-six]# cat demo_sizeof.s
	.file	"demo_sizeof.c"
	.text
	.section	.rodata
.LC0:
	.string	"%d\n"
	.text
	.globl	main
	.type	main, @function
main:
	pushq	%rbp
	movq	%rsp, %rbp
	movl	$8, %esi
	movl	$.LC0, %edi
	movl	$0, %eax
	call	printf
	movl	$16, %esi    //默认赋值16
	movl	$.LC0, %edi
	movl	$0, %eax
	call	printf
	movl	$0, %eax
	popq	%rbp
	ret
	.size	main, .-main
	.ident	"GCC: (GNU) 9.3.1 20200408 (Red Hat 9.3.1-2)"
	.section	.note.GNU-stack,"",@progbits

二. size_t

由于存放当前地址值不知当前机器平台的位数,并保证代码具有可移植性,定义一个关键字size_t在使用当前平台位数来初始化.

通过size_t获取int内存存储大小

#include <stdio.h>

int main(){
	int a = 1;
	size_t b =(size_t)&a;
	size_t c =(size_t)((&a)+1);
	printf("%d\n", c - b);
	return 1;
}

输出结果

[root@localhost second-six]# gcc demo_size_t.c
[root@localhost second-six]# ./a.out 
4

三. sizeof 和 strlen

sizeof() 算的是总空间大小,运算符

strlen() 算的是加到\0之前的大小,函数

[root@localhost second-six]# cat demo_sizeof3.c
#include <stdio.h>
#include <string.h>

int main(){
	printf("%d\n", sizeof("hello"));
	printf("%d\n", strlen("hello"));
	printf("%d\n", sizeof("hel\0lo"));
	printf("%d\n", strlen("hel\0lo"));
}

输出结果

[root@localhost second-six]# gcc demo_sizeof3.c
[root@localhost second-six]# ./a.out 
6
5
7
3
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值