遇到的c语言错误

1、输入型参数(指针)

#include <time.h>
#include <stdio.h>
	//time_t time(time_t *t);
int main(int argc,char *argv[])
{
    
    
	time_t *t = NULL;
	time(t);
	printf("the second is %ld \n",*t);	
	return 0;
}

在这里插入图片描述
错误:发生了段错误

分析:我们只传入了一个空指针,它并没有指向任何变量。所以他是无法“装下任何东西的”,所以我们在解引用的时候并没有任何意义

如果我们将变量比作一个容器, 把容器内部的东西比作水

int a=5;

指针本身只能“装容器的地址”,并不能装水。

修改:将我们的指针,指向一个变量,这样才可以间接进行读取

int main(int argc,char *argv[])
{
    
    
	time_t *t_p = NULL;
	time_t t = 0;
	t_p = &t;
	
	time(t_p);
	printf("the second is %ld \n",*t_p);
		
	return 0;
}

在这里插入图片描述

2、返回值为 char * 的函数

#include <time.h>
#include <stdio.h>
	
char *ctime(const time_t *timep);
int main(int argc,char *argv[])
{
    
    
	// time 函数变量定义
	time_t *t_p = NULL;
	time_t t = 0;
	t_p = &t;

	// ctime 函数变量定义
	char *p_ctime = NULL;
	
	//time 函数应用
	time(t_p);
	printf("the second is %ld \n",*t_p);
	
	//ctime 函数应用
	p_ctime = ctime(t_p);
	printf("%s\n",p_ctime);
		
	return 0;
}

在这里插入图片描述

总结:返回值为 char * 的函数,这个指针指向字符串的首地址。 既然可以返回 char * 指针,则说明这个字符串已经存在。

3、返回值为 struct tm * 结构体指针的函数

#include <time.h>
#include <stdio.h>
	
struct tm *gmtime(const time_t *timep);
int main(int argc,char *argv[])
{
    
    
	// time 函数变量定义
	time_t *t_p = NULL;
	time_t t = 0;
	t_p = &t;

	// ctime 函数变量定义
	char *p_ctime = NULL;
	
	// gmtime 函数变量的定义
	struct tm *p_gmtime = NULL;
	
	//time 函数应用
	time(t_p);
	printf("the second is %ld \n",*t_p);
	
	//ctime 函数应用
	p_ctime = ctime(t_p);
	printf("%s\n",p_ctime);
	
	//gmtime函数的应用
	p_gmtime = gmtime(t_p);
	printf("%d年. %d月. %d日\n",p_gmtime->tm_year,p_gmtime->tm_mon,p_gmtime->tm_mday);
	
	return 0;
}

总结:返回的是结构体指针,说明这个结构体在这个函数当中已经存在。我们可以通过结构体指针来间接引用他。
在这里插入图片描述

4、char *p[ ] 和 char **p 一样

char *p[ ] :字符串数组
char **p :可以指向字符串数组

猜你喜欢

转载自blog.csdn.net/vincent3678/article/details/112192623