查找数组值的函数
typedef int elemtype;
typedef enum
{
nullpoint = 1,
outofrance = 2,
success = 3,
fault = 4
}tagtype;
typedef struct
{
tagtype utype;
union{
int index;
elemtype value;
};
}status;
status findvalue(const int *br, const int n, const int val)
{
status res = { fault, -1 };
if (NULL == br)
{
res.utype = nullpoint;
return res;
}
if (n < 1)
{
res.utype = outofrance;
return res;
}
for (int i = 0; i < n; ++i)
{
if (val == br[i])
{
res.utype = success;
res.index = i;
break;
}
}
return res;
}
status getitem(const int *ar,int n,int index)
{
status res = { fault };
if (NULL == ar)
{
res.utype = nullpoint;
return res;
}
if (index < 0||index>=n)
{
res.utype = outofrance;
return res;
}
res.value = ar[index];
return res;
}
void main()
{
while (1)
{
system("cls");
int ar[] = { 12, 34, 56, 78, 23, 45, 67, 89, 100, 80 };
int n = sizeof(ar) / sizeof(ar[0]);
int val;
cin >> val;
int index;
cin >> index;
cout << getitem(ar, n, index).value;
cout << "退出 n" << endl;
char x;
cin >> x;
if (x == 'n')
break;
}
}
my_meset()
void my_meset(void *vp, int c, int n,int x)
{
if (NULL == vp || n < 1)return;
char *p = (char*)vp;
for (int i = 0; i < n; i++)
{
*p = c;
p++;
}
}
void main()
{
char str[10];
int ar[10];
double dr[10];
my_meset(str, 10, sizeof(str),sizeof(str[0]));
cout << str[0]<<endl;
my_meset(ar, 10, sizeof(ar), sizeof(ar[0]));
my_meset(dr, 10, sizeof(dr), sizeof(dr[0]));
}
写一个my_memcpy
struct node
{
int a;
char b;
};
#defne DEBUG
enum status {point1error,point2error};
void *my_memcpy(const void *p1, void *p2, unsigned int n)
{
#ifdef DEBUG
if ((p1 == NULL) || (p2 == NULL))
{
return NULL;
}
#endif
char *p3 = (char*)p1;
char *p4 = (char*)p2;
while (n--)
{
*p4++ = *p3++;
}
return p2;
}
void main()
{
node a = { 3, 'm' };
node b;
node c;
my_memcpy(&a, &b, sizeof(node));
my_memcpy(my_memcpy(&a, &b, sizeof(node)), &c, sizeof(node));
}
#ifdef DEBUG
#endif
这是另一种宏定义的方式,当我们给DEBUG进行#define的宏定义时那么程序中的判断指针是否为NULL就会起作用,若不进行定义则在编译的过程中会把判空函数给自动取消编译。
也可以这么操作
#ifdef YHP(宏名) #ifndef YHP(和前面的功能相反)后面是未定义宏名就进行之下内容
。。。 。。。
。。。 。。。
#else #else
。。。 。。。
。。。
#endif #endif
还有一种做法
#if 0 #if 1
.。。 。。。
#else #else
。。 。。。
#endif #endif
除了这种手写的通过宏定义的方式来确定是否判空之外还可以使用系统自带的函数assert
#include<assert.h>
assert(p1!=NULL||p2!=NULL);
memove和memcpy他们的作用是一样的,唯一的区别是,当内存发生局部重叠的时候,memmove保证拷贝的结果是正确的,memcpy不保证拷贝的结果的正确。