zoukankan      html  css  js  c++  java
  • 定义指针变量作为返回值函数执行时报 段错误(核心已转储)

    函数名称: strsspn

    函数功能: 在dest 字符串中找到首次在src字符串出现的字符,并记录该字符在src字符串中出现的次数。没有返回0。

    int strsspn(const char *dest,const char *src ,int *res){
    char* init_src= (char*)src;
    while(*dest!=''){
    while(*src!=''){
    if(*dest==*src){    
    (*res)++;    }
    src++;
    }
    if(*src==''&&*res!=0)
    return 0;
    dest++;
    src=init_src;
    }
    return 0;
    }
    int main(void){
    int *result; //申请字符指针变量;
    char *str1="mmaaabbbbbbdddddd";
    char *str2="hhiiddjjjdddd";
    *result =0;
    strsspn(str1,str2,result);
    printf("The number of str1 show in str2: %d
    ",*result);//输出str1字符串中字符首次在str2中出现的次数。
    return 0;
    }

    编译执行上述代码,gcc 提示:段错误(核心已转储)

    分析: 申请指针变量应该动态分配存储空间并赋初值。

    int *result =malloc(sizeof(int)); 

    代码纠正如下:

     1 int strsspn(const char *dest,const char *src ,int *res){
     2         char* init_src= (char*)src;
     3         while(*dest!=''){
     4             while(*src!=''){
     5                  if(*dest==*src){
     6                     (*res)++;                    
     7                 }
     8                 src++;
     9             }
    10             if(*src==''&&*res!=0)
    11                     return 0;
    12                 dest++;
    13                 src=init_src;
    14         }
    15         return 0;
    16 }
    17 int main(void){
    18     int *result =(int*)malloc(sizeof(int));
    19     char *str1="mmaaabbbbbbdddddd";
    20     char *str2="hhiiddjjjdddd";
    21     *result =0;
    22     if(result !=NULL){
    23         strsspn(str1,str2,result);
    24     }else
    25         return -1;
    26     
    27     printf("The number of str1 show in str2:  %d
    ",*result);
    28     free(result);
    29     return 0;
    30 }
  • 相关阅读:
    python学习手册 (第3版)
    服务器搭建
    阿里云 大数据 云计算 分布式
    PS插件开发plugin
    GIS九交模型
    人脸识别 人工智能(AI)
    Github上发布托管和下载
    RPLiDAR 激光雷达探测地面高程
    linux内核调试
    convex hull
  • 原文地址:https://www.cnblogs.com/Liangzilv/p/9597057.html
Copyright © 2011-2022 走看看