void和void指针的用法

void 的作用

  1. 对函数返回的限定,函数不需要返回值时
 void fun(int a,int b)
  1. 函数参数的限定,函数不需要形参时
 int fun(void)

void *指针(无类型指针)

  1. void 指针可以指向任意类型的数据,任意类型的指针都可以对void指针赋值(“无类型”可以包容“有类型”
int *A;
void *p;
p=A;
  1. void 指针赋值给其他类型的指针,需要强制类型转换(“有类型”并不包容“无类型”
int *A;
void *p;
A=(int *)p;
  1. 内存分配函数malloc函数返回的指针是void*型,在使用malloc时,需要强制类型转换
char *str;
str=(char *) malloc(20)

注:ANSI标准中,不允许对void指针进行算术运算如p++或p+1等

void* 指向用法

指向变量

在这里插入图片描述

指向字符串

#include <stdio.h>

int main()
{
    
    
	char *b="abcdefg";
	void *p=b;	
	printf("%s \r\n",(char*)p);  //转换不转换为 char* 均可以,打印指针指向的字符串无需解引用
//	printf("%s \r\n",p);
	printf("%c \r\n", *(char*)p); //打印单个字符 需要转换并解引用
 } 
#include <stdio.h>

int main()
{
    
    
	char b[]="abcdefg";
	void *p=b;	
	printf("%s \r\n",(char*)p);  //转换不转换为 char* 均可以,打印指针指向的字符串无需解引用
//	printf("%s \r\n",p);
	printf("%c \r\n",*(char *)p)}

指向结构体

#include <stdio.h>
#include <string.h>

typedef struct{
    
    
	char name[10];
	int age;
}student;

int main()
{
    
    
	student per;
	void *p;
	strcpy(per.name,"ZhangLi");
	per.age=22;
	
	p=&per;  //指向结构体 
	printf("%s %d\r\n",((student*)p)->name,((student*)p)->age);  //类型转换 
	return 0;

}

猜你喜欢

转载自blog.csdn.net/weixin_44333597/article/details/107634020