【问题标题】:Substring function in C [closed]C中的子字符串函数[关闭]
【发布时间】:2020-12-22 22:56:45
【问题描述】:

我正在尝试在 C 中创建子字符串函数,这非常合乎逻辑且容易,但由于某种原因它会打印出符号。我在网上查了很多次,对比其他人的功能,但我找不到我的代码不起作用的确切原因。

#define MAX 50

char* substring(char string[], int indexBeginning, int indexEnd) {
    const char *result[MAX];
    int n= 0;

    for (int i = indexBeginning; i <= indexEnd; i++) {
        result[n++] = string[i];
    }
    result[n] = '\0';

    return result;
}

【问题讨论】:

  • result is 1) 类型不正确(应该是char []) 2) 是本地的,无法返回
  • malloc - 是的,const - 没有。是什么让你如此相信?
  • result[n++] = string[i]char 值(提升为int)分配给char * 指针对象。这需要诊断。 result 是指针数组,而不是字符数组。
  • 请打开编译器警告,看看这段代码有什么问题。
  • @JustCaused 我认为你混淆了conststatic。使用声明static char result[MAX],您可以return result;。但是每次调用该函数时,旧的result 都会被覆盖。

标签: c substring c-strings function-definition


【解决方案1】:

这个数组声明

const char *result[MAX];

不正确。看来你的意思

char result[MAX];

但是在任何情况下你都不能使用数组作为返回表达式

return result;

因为数组是函数的本地对象,退出函数后就不会存活了。

也是这个循环

for (int i = indexBeginning; i <= indexEnd; i++) {
    result[n++] = string[i];
}

不安全,因为没有检查指定的索引是否对源字符串有效。

并且函数本身应该声明为

char * substring( const char string[], size_t pos, size_t n );

该函数可以通过以下方式定义,如下面的演示程序所示。

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

char * substring( const char s[], size_t pos, size_t n )
{
    char *result = NULL;
    
    size_t length = strlen( s );
    if ( pos < length )
    {
        n = n <= length - pos ? n : length - pos;
        
        result = malloc( n + 1 );
        
        if ( result != NULL )
        {
            result[n] = '\0';
            
            memcpy( result, s + pos, n );
        }
    }
    
    return result;
}

int main(void) 
{
    const char *s = "Hello World!";
    
    char *word = substring( s, 0, 5 );
    
    if ( word ) puts( word );
    
    free( word );
    
    word = substring( s, 6, 5 );

    if ( word ) puts( word );
    
    free( word );
    
    return 0;
}

程序输出是

Hello
World

【讨论】:

  • 我对 const 而不是 static 感到困惑,这似乎现在可以工作。在我断言索引之前起作用,但感谢您的建议!
猜你喜欢
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多