C 如何返回字符数组并在main中打印它?
我构建了一个函数,它获取一个整数参数并返回一个字符数组 例如,对于参数13,函数应返回0013;对于参数3,函数应返回0003 但是我没有得到一个错误,我不能用printfgetInstructionIndex13显示这个值 这是我的密码:C 如何返回字符数组并在main中打印它?,c,arrays,function,char,main,C,Arrays,Function,Char,Main,我构建了一个函数,它获取一个整数参数并返回一个字符数组 例如,对于参数13,函数应返回0013;对于参数3,函数应返回0003 但是我没有得到一个错误,我不能用printfgetInstructionIndex13显示这个值 这是我的密码: /* get Instruction Index how "0001" or "0010" */ char * getInstructionIndex(int index){ char number1; char number2;
/* get Instruction Index how "0001" or "0010" */
char * getInstructionIndex(int index){
char number1;
char number2;
char number3;
char *str = (char *) malloc(sizeof(char) * 4);
if(index < 10){
number1 = '0';
number2 = '0';
number3 = '0';
str[0] = number1;
str[1] = number2;
str[2] = number3;
str[3] = index;
return str;
}
else{
if(index < 100 && index >= 10){
number1 = '0';
number2 = '0';
str[0] = number1;
str[1] = number2;
str[2] = index;
return str;
}
else
{
if(index < 1000 && index >= 100){
number1 = '0';
str[0] = '0';
str[1] = index;
return str;
}
else
{
str[0] = index;
return str;
}
}
}
free(str);
}
如果此代码中存在内存泄漏,则空闲时间应延迟到打印阵列后,例如:
char *str = getInstructionIndex(13)
printf("%s", str); /* i must see 0013*/
free(str);
如果要打印函数返回的字符串,应使用:
printf("%s", str);
还有一件事,您在getInstructionIndex方法中构造的值需要由字符串终止符\0终止,否则您将在输出中获得垃圾。如果此代码中存在内存泄漏,则空闲值应延迟到打印数组后,例如:
char *str = getInstructionIndex(13)
printf("%s", str); /* i must see 0013*/
free(str);
如果要打印函数返回的字符串,应使用:
printf("%s", str);
还有一件事,您在getInstructionIndex方法中构造的值需要由字符串终止符\0终止,否则您将在输出中得到垃圾。
string str只分配了4个字符,对于null终止符来说不够
未添加空终止符
复杂逻辑
内存泄漏
缺少格式说明符
铸造马洛克返回
调整代码
参考文献
问题
string str只分配了4个字符,对于null终止符来说不够
未添加空终止符
复杂逻辑
内存泄漏
缺少格式说明符
铸造马洛克返回
调整代码
参考文献
y不只是使用printf%04d,而是someInteger;请注意,强制转换malloc的返回值被认为是不好的做法。请参阅,y不只是使用printf%04d,someInteger;请注意,强制转换malloc的返回值被认为是不好的做法。请参阅更改为使用sizeof*str以与链接一致。并添加了安全保护,以在无效输入无法以5个字符打印时返回null,包括将null终止符更改为使用sizeof*str以与链接一致。并增加了安全保护,以在出现无效输入时返回null,该输入不能以5个字符(包括null终止符)打印
$ gcc -g test.c -o test
$ valgrind ./test
==2713== Memcheck, a memory error detector
==2713== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==2713== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==2713== Command: ./test
==2713==
started
0013
stopped
==2713==
==2713== HEAP SUMMARY:
==2713== in use at exit: 0 bytes in 0 blocks
==2713== total heap usage: 1 allocs, 1 frees, 5 bytes allocated
==2713==
==2713== All heap blocks were freed -- no leaks are possible
==2713==
==2713== For counts of detected and suppressed errors, rerun with: -v
==2713== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)