gpt4 book ai didi

c - 如何返回一个 char 数组并在 main 中打印它?

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:15 25 4
gpt4 key购买 nike

我构建了一个获取整数参数并返回字符数组的函数。

例如,对于参数 13,函数应返回“0013”;对于参数 3,函数应返回“0003”。

但我没有收到错误,我无法使用 printf(getInstructionIndex(13)); 显示此值

这是我的代码:

/* 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);

}

这是我的主要内容:

int main(int argc, char *argv[]){

printf("started\n");


printf(getInstructionIndex(13)); /* i must see 0013*/

printf("stopped\n");

return 0;
}

最佳答案

问题

  • string str allocated only 4 chars, not enough for null terminator
  • null terminator not added
  • complex logic
  • memory leak
  • missing format specifier
  • casting malloc return

调整后的代码

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

/* get Instruction Index how "0001" or "0010" */
char * getInstructionIndex(int index){
/* overflow + underflow handling */
if(index < 0 || index > 9999)return 0;

/* allocate enough for the null terminator.. */
char *str = malloc(sizeof(*str) * 5);
/* error handling */
if(!str)
{
return 0;
}

/* simplify logic, use a nice format specifier */
sprintf(str, "%04d", index);
return str;
}

int main(int argc, char *argv[])
{
char *instruction_index;
printf("started\n");
instruction_index = getInstructionIndex(13);
if(!instruction_index)
{
// error handling here..
return 0;
}
/* add format string.. */
printf("%s\n", instruction_index); /* i must see 0013*/
/* release the memory */
free(instruction_index);
printf("stopped\n");
return 0;
}

输出

$ 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)

引用

关于c - 如何返回一个 char 数组并在 main 中打印它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com