首页 > 解决方案 > 无法通过c中的函数传递字符串

问题描述

我正在学习 c 并使用字符串、函数和指针进行一些练习。练习是将字符串放入函数中,进行详细说明并给出结果。函数 'LenCorr' 在输入字符串的末尾添加 'i' 字母以实现 8 个字符的长度。

我的代码是:

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

#define StrLen 100

char * LenCorr(char * str);

void main(void)
{
    char t1[StrLen] = "Hello3"; // this is the input string
    printf("Input : %s\n", t1);  
    
    char *t3 = LenCorr(t1);     // pass through the 'LenCorr' function to t3 pointer to char array
    printf("LenCorr p: %p\n", t3); // then I print the pointer ...
    printf("LenCorr s: %s\n", t3); // ... but the content is empty
}

char * LenCorr(char * str)
{
    char si[StrLen]; // I create various strings
    char su[StrLen];
    char st[StrLen] = "iiiiiiiiiiiiiiiiiii";
    
    strcpy(si,str); // I have to copy the 'str' input to the local string

    // here I perform some elaborations
    int ln = strlen(si);
    int ct = 8 - ln;
    
    if (ln < 8) {strncat(si, st, ct);}

    // ... and the final result is correct into 'si' string
    strcpy(su,si); // that I copy into a 'su' string (another)

    char * output = su;
    
    printf("Debug output: %s\n", output); // here I see the result of string elaboration 
    printf("Debug output pointer: %p\n", output); // here I get a pointer of the string elaboration

    return output;
}

但最后该函数返回正确的指针值,但值为 0。这里控制台输出:

Input : Hello3
Debug output: Hello3hh
Debug output ptr: 0x7fff4cf17c30
LenCorr p: 0x7fff4cf17c30
LenCorr s: 

为什么 ?

标签: cstringfunctionpointers

解决方案


我认为,在 c 中,不使用函数的返回数组和字符串更有用,但最好使用指向目标变量的指针作为参数。在示例中,该函数应如下定义:

LenCorr(char * ret, char * str)

其中'ret'是指向返回变量的参数。

完整的代码变成了:

void main(void)
{
    char t1[StrLen] = "Hello3"; // this is the input string
    char t3[StrLen]
    printf("Input : %s\n", t1);  
    
    LenCorr(t3, t1);     // pass through the 'LenCorr' function to t3 pointer to char array
    printf("LenCorr p: %p\n", t3); // then I print the pointer ...
    printf("LenCorr s: %s\n", t3); // ... but the content is empty
}

int LenCorr(char * ret, char * str)
{
    char si[StrLen];
    
    strcpy(si, str);
    
    //.... various code ....

    strcpy(ret, si);
}

推荐阅读