C语言函数返回值为指针和函数返回值为void

本文通过几个具体的C语言实例介绍了如何使用sprintf函数进行字符串格式化,并演示了指针变量的定义与使用方法,包括内存分配、复制字符串等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时遇到函数返回值为空和函数返回值为指针的情况下,需要在前面定义该函数
//函数的返回值为指针也必须在此定义,
//函数的返回值为void必须在此定义,返回值是整形或者其他基本类型不需要在此定义

函数功能:把格式化的数据写入某个字符串
函数原型:int sprintf( char *buffer, const char *format [, argument] … );
返回值:字符串长度(strlen)

#include 

void main(){

char* who = "I";
char* whom = "优快云";
char s[30];
sprintf(s, "%s love %s.", who, whom); //产生:"I love 优快云. "  这字符串写到s中
printf("%s\n",s);
sprintf(s, "%10.3f", 3.1415626); //产生:" 3.142"
printf("%s\n",s);
sprintf(s,"hejianghzou");
printf("%s\n",s);


}


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

char * test3();    //函数的返回值为指针也必须在此定义,
void test2(void);	//函数的返回值为void必须在此定义,返回值是整形或者其他基本类型不需要在此定义
					
void main(void)
{
	char *cp;
//	const int two = 2;
	test2();
	cp = test3();
	printf(cp);

}
 void test2(void)
{
	int i = 0;
	char *available_resources[] = {"afbhd","gbjaf","dajgb","kcdbha"};
	for(i;i<4;i++){
		printf("\n ");
		printf(available_resources[i]);
		printf("\n");
	}

}
char *test3()
{
	
	char *tempbuffer ;
	char buffer[120] ;
	tempbuffer = (char*)malloc(100*sizeof(char));
	memcpy(tempbuffer,"That'd be in the data segment ,bob",100);
	printf(tempbuffer);
	strcpy(buffer,(char*)"Game's over");
	return buffer;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值