函数返回数组的非常规实现

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char* squeeze(char s1[] ,char s2[]){
int i,j,k = 0;

static char s[MAXSIZE];
for(i = 0; s1[i] != '\0' ;i++){
    for(j = 0 ; s2[j] != s1[i] && s2[j] != '\0';j++)
    ;
    if(s2[j] == '\0')
        s[k++] = s1[i];
}
s[k] = '\0';
return s;
}
int main(int argc, char *argv[]) {
int i,j;
char a[MAXSIZE],p[MAXSIZE],*b;

printf("please input an string:\n");
scanf("%s",&a);
printf("please input the pattern:\n");
scanf("%s",&p);

b = squeeze(a,p);
printf("after:the test:%s\n",b);
}

这是指针返回字符串的简单实现。
返回一个数组的首字母,函数实际上返回的是数组的开始地址,在主函数中用一个指针去获取就可以

注意!!!

因为所返回的是函数局部变量的地址,而局部变量在函数被调用完后即被销毁,此时主函数拿到的地址就变成了一个无效的地址,所以在函数中我们要把数组用static限定,使他的作用域扩展到整个空间

这种方法并不是特别合适,建议用个空数组作为参数给被调函数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值