20240510 内存管理的相关函数
明昧 Lv7

strcpy

将源头指向的C字符串复制到目标指向的数组中,包括结尾的’/0’字符,并在’\0’字符处停止拷贝.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#define _CRT_SECURE_NO_WARNINGS 1

/* strcpy example */
#include <stdio.h>
#include <string.h>

int main()
{
char str1[] = "Sample string";
char str2[40]={0};
printf("str1: %s\nstr2: %s\n", str1, str2);

strcpy(str2, str1);
printf("str1: %s\nstr2: %s\n", str1, str2);

return 0;
}

strlen

size_t strlen ( const char * str );

strlen函数是C语言中的一个字符串处理函数,其主要用途是计算一个字符串的长度。它接受一个指向字符串的指针作为参数,并返回一个整数值,表示字符串的长度**(不包括空字符’\0’)**。

使用strlen函数必须添加头文件 #include <string.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <string.h>

int main()
{
if (strlen("abc") - strlen("abcdef") > 0)
{
printf(">=\n");
}
else
{
printf("<\n");
}

return 0;
}

如果从数学的角度去分析的话,strlen(“abc”)的长度是3,strlen(“abcdef”)的长度是6,3-6的结果是-3呀,打印出来的结果就应该是<。

但实际上当我们去运行这个代码的时候会发现打印出来的结果为>=。

image-20240615121737441

为什么是>=呢,就是因为strlen的返回值为无符号整型size_t,而两个无符号数相减得到的还是无符号数,当-3被当作无符号数的时候得到的会是一个非常大的正数,肯定是>0的,所以运行结果就为>=。

模拟实现strlen

https://blog.csdn.net/weixin_65931202/article/details/133608862

 Comments
Comment plugin failed to load
Loading comment plugin
Powered by Hexo & Theme Keep
Unique Visitor Page View