gpt4 book ai didi

c - 如何在同一行上打印所有数组元素?

转载 作者:行者123 更新时间:2023-11-30 21:30:58 25 4
gpt4 key购买 nike

我不得不删除所有代码。我正在寻找的是如何在同一行中 sprintf 数组的所有元素。

显示有2行,我需要打印数组10,24,32,40,51,.....第一行 和 10,51 .....第二行

最佳答案

样本

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

char *join(int n, const int array[n], const char *format, const char *sep){
if(!format)
format = "%d";
if(!sep)
sep = ", ";
size_t len = strlen(sep)*(n-1)+1;//+1 for EOS
int i;
for(i=0;i<n;++i)
len += snprintf(NULL, 0, format, array[i]);
char *result = malloc(len);
if(!result)return NULL;
size_t pos = 0;
for(i=0;i<n;++i){
pos += sprintf(result + pos, format, array[i]);
if(i != n-1)
pos += sprintf(result + pos, "%s", sep);
}
return result;
}

int main (void){
int array[][5]={{10,24,32,40,51},{10,1,99,77,88}};
int row_size = sizeof(array)/sizeof(array[0]);
int col_size = sizeof(array[0])/sizeof(int);
char *join_str;
int i;
for(i=0;i<row_size;++i){
char *join_str = join(col_size, array[i], "%2d", ", ");
printf("%s\n", join_str);
free(join_str);
}
return 0;
}

关于c - 如何在同一行上打印所有数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21794668/

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