✨博客主页: XIN-XIANG荣
✨系列专栏:【从0到1,C语言学习】
✨一句短话:你若盛开,蝴蝶自来!
✨博客说明:尽己所能,把每一篇博客写好,帮助自己熟悉所学知识,也希望自己的这些内容可以帮助到一些在学习路上的伙伴,文章中如果发现错误及不足之处,还望在评论区留言,我们一起交流进步!😊
😽这里介绍atoi、offsetof以及它们的模拟实现,atoi这个库函数用来将一个字符串转化为一个数字;offsetof用来计算偏移量,长的像个函数,其实它是一个宏!
功能:
int atoi (const char * str);
头文件:
参数:
返回值:
注意事项:
使用实例:

atoi的模拟要尽可能模拟全面,要考虑到如下几点:
#include
#include
#include
#include
enum Status
{
VALID,
INVALID
}sta = INVALID;//默认非法
int My_atoi(const char* str)
{
int flag = 1;
assert(str);
if (*str == '\0')
{
return 0;//返回的非法0
}
//跳过空白字符
while (isspace(*str))
{
str++;
}
//解决+-号
if (*str == '+')
{
flag = 1;
str++;
}
else if (*str == '-')
{
flag = -1;
str++;
}
long long ret = 0;
while (*str)
{
if (isdigit(*str))
{
ret = ret * 10 + flag * (*str - '0');
//判断越界
if (ret > INT_MAX || ret < INT_MIN)
{
return 0;
}
}
else
{
return (int)ret;
}
str++;
}
if (*str == '\0')
{
sta = VALID;
}
return (int)ret;
}
int main()
{
char arr[50] = "-1234";
int ret = My_atoi(arr);
if (sta == INVALID)
{
printf("非法返回:%d\n", ret);
}
else if(sta == VALID)
{
printf("合法转换:%d\n", ret);
}
return 0;
}
功能:
offsetof (type,member)
参数:
返回值:
使用实例:

去观察结构体的地址和结构成员的地址会发现,结构体成员的地址减去结构体的地址就是结构体成员相对于结构体首地址的偏移量;
假设0地址处为结构体的地址,那么结构体成员的地址就是其的相对于结构体首地址的偏移量
#include
#define OFFSETOF(type, name) (int)&(((struct S*)0)->name)
struct S
{
int a;
char b;
double c;
};
int main()
{
printf("%d\n", OFFSETOF(struct S, a));
printf("%d\n", OFFSETOF(struct S, b));
printf("%d\n", OFFSETOF(struct S, c));
return 0;
}
各位小伙伴,看到这里就是缘分嘛,希望我的这些内容可以给你带来那么一丝丝帮助,可以的话三连支持一下呗😁!!! 感谢每一位走到这里的小伙伴,我们可以一起学习交流,一起进步😉!!!加油🏃!!!
