【问题标题】:How I can save a char variable into a char* structure?如何将 char 变量保存到 char* 结构中?
【发布时间】:2021-12-12 07:23:49
【问题描述】:

我的任务是计算一个数字的阶乘,保存到一个结构中然后打印出来。

结构体代码如下:

struct fact_entry
{                               /* Definition of each table entry */
    int n;
    long long int lli_fact;       /* 64-bit integer */
    char *str_fact;
};

之后是下一个代码。我已经定义了一个 long long int 变量来计算阶乘,并且将这个数字首先保存到结构的元素中没有问题,打印功能可以正常工作。问题在于 char *str_fact;变量,我编写了一个代码来使用 sprintf 将 int 值更改为 char,但是在我将此值分配给结构后,在下一个 for 循环中它只打印计算的最后一个元素。如果我尝试在第一个循环内打印它,一切正常,但在外面它只打印最后一个。

int
main (int argc, char *argv[])
{
    int n;
    int i;
    struct fact_entry *fact_table;

    if (argc != 2)
        panic ("wrong parameters");

    n = atoi (argv[1]);
    if (n < 0)
        panic ("n too small");
    
    if (n > LIMIT)
        panic ("n too big");

/* Your code starts here */
    // Allocate memory
    // Compute fact(n) for i=0 to n
    fact_table = calloc(n+1, sizeof(struct fact_entry));
    long long int f=1;
    char buf[20];
    for (i = 0; i <= n; i++)
    {
        if (i == 0) { 
            f = f * i + 1;;
        }
        else{
            f=f*i;
        }
     
        sprintf(buf, "%lld", f);
        printf("%s\n", buf);
        fact_table[i].n = i;
        fact_table[i].lli_fact = f;
        fact_table[i].str_fact = buf;      
    }
    /* Your code ends here */

    // print computed numbers
    for (i = 0; i <= n; i++)
    {
        printf ("%d %lld %s\n", fact_table[i].n, fact_table[i].lli_fact, fact_table[i].str_fact);
    }

    /* Your code starts here */
    // Free memory
    free(fact_table);
    /* Your code ends here */

    return 0;
}

如何将 buf 变量写入结构。我只能更改/*your code */之间的代码

【问题讨论】:

    标签: c pointers char structure factorial


    【解决方案1】:
    char buf[20];
    ...
    fact_table[i].str_fact = buf;
    

    str_fact是一个指针,指向buf。您有 n + 1 元素,它们都指向同一个 buf,它们都打印您在输出中看到的最后一个元素。

    您必须为每个str_fact 分配内存,以便它可以存储自己的字符串。记住也要为该缓冲区释放内存。

    for (i = 0; i <= n; i++)
    {
        ...
        //fact_table[i].str_fact = buf; *** remove this line
        fact_table[i].str_fact = malloc(strlen(buf) + 1);
        strcpy(fact_table[i].str_fact, buf);
    }
    
    for (i = 0; i <= n; i++)
        free(fact_table[i].str_fact);
    free(fact_table);
    

    请注意,您正在分配 n + 1 元素。如果您需要 n 元素,则在所有循环中数到 i &lt; n

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 2020-08-14
      • 2013-05-15
      • 2021-01-24
      • 2014-02-27
      • 1970-01-01
      相关资源
      最近更新 更多