C程序设计问题

C程序设计问题,c,C,我正在使用sprintf打印int变量,该变量应显示1^2+2^2+3^2+4^2+5^2+6^2。但是我的代码只打印1^2+6^2。我不知道为什么中间部分不见了 #include <stdio.h> #include <stdlib.h> #include <string.h> char* formatSeries(int n) { char *tagstr = (char *)malloc(sizeof(char)*n*n); int pos

我正在使用
sprintf
打印
int
变量,该变量应显示
1^2+2^2+3^2+4^2+5^2+6^2
。但是我的代码只打印
1^2+6^2
。我不知道为什么中间部分不见了

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

char* formatSeries(int n)
{
  char *tagstr = (char *)malloc(sizeof(char)*n*n);

  int pos = 0 ;
  int k;

  for (k = 1; k <= n; k++)
  {
    pos = sprintf(&tagstr[pos], "%d^2+", k);
  }
  tagstr[strlen(tagstr) - 1] = '\0';

  return tagstr;
}

 void main()
{
  int n = 6;
  printf("%s \n", formatSeries(n));
}
#包括
#包括
#包括
字符*格式系列(整数n)
{
char*tagstr=(char*)malloc(sizeof(char)*n*n);
int pos=0;
int k;

对于(k=1;k您的代码中有两个主要问题;正如评论中已经提到的,一个问题是您没有增加
pos
,而是用(几乎)相同的值一次又一次地重新分配它。因此,在第一次迭代之后,您将不断地写入
4
(或
5
如果
k
将变成>=10,则数字将因此获得更多的数字)


其次,您的
malloc
对于较小的
k
s不起作用,因为每个字符串都像
“+1^2”
至少需要4个字符;因此,如果您使用
n*n
调整缓冲区大小,那么如果
n
是s/
pos=sprintf
/
pos+=sprintf
?,缓冲区就会太小。是的-@a3f有它。这行也是
tagstr[strlen(tagstr)-1]='\0';
是…错误的…而且是不必要的。此外,在n=4之前,数组的初始大小不够大。此外,为什么循环从1到n而不是从0到n-1?@NoseKnowsAll可能仅用于打印。:)
char* formatSeries(int n)
{
    const size_t maxSize = n * (7+3) + 1;

    char *tagstr = (char *)malloc(sizeof(char)*maxSize);

    int pos = 0 ;
    int k;
    for (k = 1; k <= n; k++)
    {
        const char* formatStr = (k==1) ? "%d^2" : "+%d^2";
        pos += sprintf(&tagstr[pos], formatStr, k);

    }
    return tagstr;
}