c - 无法通过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:
为什么 ?
解决方案
我认为,在 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);
}
推荐阅读
- rxjs - rxjs - 点击与订阅
- powershell - 检查 UNC 路径/服务器文件夹是否存在
- java - 对 jtextfield 代码执行有限的字符范围不起作用
- reactjs - 带有动态标题和描述的 Whatsapp 共享
- php - PHP:取消链接资源暂时不可用
- java - 字符串不能转换为 double[]
- php - getenv() 在浏览器中工作,但不在命令行中
- javascript - 使用 javascript 函数返回格式化 json 数据的数据表
- javascript - 如何创建一个将任何给定字符串与第二个参数连接起来的函数?
- pdf - 如何让 Adobe Reader 生成高效的 XPS