返回一个int数组的Printf函数 [英] Printf function who returning an array of int
问题描述
我正在尝试此练习,但是我不知道如何在main中打印函数.练习:1)编写一个函数,该函数返回一个int选项卡,其中的所有值都在min和max之间
I'm trying this exercice but I don't know how to printf my function in main. Exercice: 1) Write a function who returning an int tab with all values between min and max
#include <stdlib.h>
#include <stdio.h>
int *ft_range(int min, int max)
{
int len;
int *tab;
len = min;
while (len < max)
len++;
tab = (int *)malloc(sizeof(*tab) * len + 1);
while (min < max)
{
*tab = min;
min++;
}
return(tab);
}
int main()
{
ft_range(0, 10);
return(0);
}
推荐答案
返回一个int选项卡,其中所有值都在最小值和最大值之间
returning an int tab with all values between min and max
根据之间"的概念,是否应包含最终值是一个悬而未决的问题.鉴于OP在 sizeof(* tab)* len +1
中的误编码+1,我认为应该包括两端.
Depending on the idea of "between", it is an open question if the end values should be included. Given OP's mis-coded +1 in sizeof(*tab) * len + 1
, I'll go with the idea both ends should be included.
对 len
Miscalculation of len
而不是循环,只需减去
//len = min;
//while (len < max)
// len++;
len = max - min + 1;
分配计算错误
很好使用 sizeof * pointer
,但是+ 1没什么意义.如果有的话, ... * len +1
应该是 ... *(len +1)
.+1是通过上述解决方法处理的.在 C 中也不需要强制转换.
Good to use sizeof *pointer
, yet the + 1 makes little sense. If anything the ... * len + 1
should have been ... * (len + 1)
. Yet the +1 is handled with the above fix. Also cast not needed in C.
// tab = (int *)malloc(sizeof(*tab) * len + 1);
tab = malloc(sizeof *tab * len);
错误分配
代码重复分配了相同的 * tab
位置.
Code repeatedly assigned the same *tab
location.
//while (min < max)
//{
// *tab = min;
// min++;
//}
for (int i = min; i <= max; i++) {
tab[i - min] = i;
}
没有分配错误检查,也没有最小,最大
验证
No allocation error checking nor min, max
validation
使用 mix-min
Potential for int
overflow with mix - min
一定要免费分配
替代
#include <stdlib.h>
#include <stdio.h>
int *ft_range(int min, int max) {
if (min > max) {
return NULL;
}
size_t len = (size_t)max - min + 1;
int *tab = malloc(sizeof *tab * len);
if (tab == NULL) {
return NULL;
}
for (size_t i = 0; i < len; i++) {
tab[i] = int(min + i);
}
return tab;
}
int main() {
int mn = 0;
int mx = 10;
int *ft = ft_range(mn, mx);
if (ft) {
int *p = ft;
for (int i = mn; i <= mx; i++) {
printf("%d ", *p++);
}
free(ft);
}
return 0;
}
这篇关于返回一个int数组的Printf函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!