简体   繁体   English

C编程sprinf问题

[英]C programming sprinf issue

I'm using sprintf to print int variable which should display 1^2+2^2+3^2+4^2+5^2+6^2 . 我正在使用sprintf打印int变量,该变量应显示1^2+2^2+3^2+4^2+5^2+6^2 But my code only prints 1^2+6^2 . 但是我的代码只输出1^2+6^2 I don't know why the middle part is missing. 我不知道为什么中间部分不见了。

#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));
}

There are two main issues in your code; 您的代码中有两个主要问题; the one - as already mentioned in the comments - is that you do not increase pos but reassign it again and again with (almost) the same value. 正如评论中已经提到的那样,一个问题是您不增加pos而是一次又一次(几乎)使用相同的值进行重新分配。 Hence, after the first iteration, you will constantly write to a position at 4 (or 5 if k would become >=10 and the numbers would thereby get more digits), 因此,在第一次迭代之后,您将不断地写入4的位置(如果k变得> = 10且数字将因此获得更多数字,则写入5 ),

Second, your malloc will not work for small k s, since each string like "+1^2" takes at least 4 characters; 其次,您的malloc不适用于较小的k ,因为每个字符串"+1^2"至少需要4个字符; so if you size the buffer with n * n , then the buffer will be too small if n is <= 3, and (probably much) too big if n becomes larger. 因此,如果使用n * n调整缓冲区大小,则如果n <= 3,则缓冲区将太小;如果n变得较大,则(可能太大)会太大。

I'd suggest to assume a maximum range of n (let's say up to 7 digits) and dimension the buffer accordingly. 我建议假设最大范围为n (假设最多7位数字),并相应地确定缓冲区的尺寸。

A minor thing (and not essential) is that you probably could avoid writing superfluous + at all in that you use a different format string for the first iteration; 一件小事(不是必需的)是,您可能完全避免编写多余的+ ,因为在第一次迭代中使用了不同的格式字符串。 just do show the idea, really not essential: 只是显示想法,真的不是必须的:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM