1 #include <stdio.h>
2
3 int main()
4 {
5 printf("\n");
6 int a[5] = {1,2,3,4,5};
7 int *p, **k;
8 p = a;
9 k = &p;
10 printf("%d", *(p++));
11 printf("%d", **k);
12 return 0;
13 }
14 输出结果:
15 12
16 解释:1、p指针指向a数组的首地址,printf("%d", *(p++));时输出a[0]的值。
17 2、由于p++,p的值改变指向a[1],k指向p所在地址,故*k为p中值,**k等同于*p,即a[1]。
#include <iostream>
using namespace std;
class Base
{
int x;
public:
Base(int b):x(b){}
virtual void display()
{
cout << x << endl;
}
};
class Derived : public Base
{
int y;
public:
Derived(int d):Base(d), y(d) {}
void display()
{
cout << y << endl;
}
};
int main(void)
{
Base b(2);
Derived d(3);
b.display();
d.display();
Base *p = &d;
p->display();
system("pause");
return 0;
}
运行结果:
2
3
3
解释:p->display();Derived继承了Base,但是p->display()调用的依然是子类Derived的display.
#include <stdio.h>
struct xx
{
long long _x1;
char _x2;
int _x3;
char _x4[2];
static int _x5;
};
int xx::_x5;
int main(void)
{
long long _x1;
printf("x1:%d\n[0x%p]", sizeof(_x1), &xx._x1);
char _x2;
printf("x2:%d\n", sizeof(_x2));
int _x3;
printf("x3:%d\n", sizeof(_x3));
char _x4[2];
printf("x4:%d\n", sizeof(_x4));
printf("x5:%d\n", sizeof(xx::_x5));
printf("%d", sizeof(xx));
return 0;
}
运行结果:
x1:8
x2:1
x3:4
x4:2
x5:4
24
解释:字节对齐问题,8+4(1)+4+4(2)+4=24
春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct node)
double findvalue = 0.0;
struct node
{
double value;
int num;
struct node * pleft;
struct node * pright;
};
struct node * head = (struct node *)malloc(LEN);
void insertTree(double temp, struct node * p)
{
if(p->value == 0)
{
p->value = temp;
}
else if(temp>p->value)
{
if(p->pright == NULL)
{
p->pright = (struct node *)malloc(LEN);
p->pright->value = 0;
p->pright->num = 1;
p->pright->pleft = NULL;
p->pright->pright = NULL;
}
insertTree(temp, p->pright);
}
else if(temp<p->value)
{
if(p->pleft == NULL)
{
p->pleft = (struct node *)malloc(LEN);
p->pleft->value = 0;
p->pleft->num = 1;
p->pleft->pleft = NULL;
p->pleft->pright = NULL;
}
insertTree(temp, p->pleft);
}
else if(temp == p->value)
{
p->num ++;
}
}
void findTree(struct node * p, int n)
{
if(p->pleft!=NULL) findTree(p->pleft, n);
if(p!=NULL)
{
if(p->num > n/2) findvalue = p->value;
}
if(p->pright!=NULL) findTree(p->pright, n);
}
int main(void)
{
int n;//红包总数
double temp;//单个红包金额
while(scanf("%d",&n)!=EOF)
{
scanf("%lf", &temp);
head->value = temp;
head->num = 1;
head->pleft = NULL;
head->pright = NULL;
for(int i=1; i<n; i++)//建立相同金额的红包树形结构。value记录红包金额,num记录红包个数
{
scanf("%lf", &temp);
insertTree(temp, head);
}
findTree(head,n);//查找相同金额数大于总数一半的红包金额
printf("%lf", findvalue);//输出相同金额数大于总数一半的红包金额
}
return 0;
}