关于C指针问题的再谈
#include <iostream> #include <algorithm> #include <cstdio> using namespace std; int main(){ int a=10; int *p; p=&a; cout<<*p<<endl; return 0; }
printf 语句中*p 中的* 号叫做间接运算符,作用是取得指针p 所指向的内存中的值。
* 号的3个用处;
1.乘号
2.声明一个指针,在定义指针变量时使用。
3.间接运算符,取得指针所指向的内存中的值。
---------------------------------------------------------------------------------
malloc 函数
作用:从内存中申请分配指定字节大小的内存空间。
怎么对这个空间进行操作呢?
需要指针来指向这个空间。
即 存储这个空间的首地址。
-----------------------------------------------------------------------------------
int *p; p=(int *)malloc(sizeof(int));
注意:
malloc 函数返回类型是 void * 类型。
void * 类型可以强制转换为任何其他类型的指针
在使用malloc 函数时要用到 stdlib.h 头文件。
------------------------------------------------------------------------------------
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main(){
int *p;
p=(int *)malloc(sizeof(int));
*p=10;
cout<<*p<<endl;
getchar();
getchar();
return 0;
}
为什么要用这么复杂的方法来存储数据呢?
之前的方法,我们必须预先准确地知道所需变量的个数,也就是说必须定义出所有的变量。
malloc 函数可以在程序运行的过程中根据实际情况来申请空间。
-------------------------------------------------------------------------------------
如何建立链表?
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
struct node
{
int data;
struct node *next;
};
int main(){
struct node *head,*p,*q,*t;
int i,n,a;
cin>>n;
head = NULL;
for(i=1;i<=n;i++){
cin>>a;
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
t=head;
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}
getchar();
getchar();
return 0;
}
本文来自博客园,作者:小白兔奶糖, 侵权必究!!!







浙公网安备 33010602011771号