我正在学习指针并进行练习,在该过程中,我将动态创建一个指针并接受来自用户的输入,然后将用户输入的两倍存储到动态创建的指针中,并将其打印到控制台。我遇到的问题是,它不会打印出两倍的用户条目,我已经对其进行了调试,并且看起来t变量没有保存两倍的用户条目,并且我不确定如何解决此问题。

我已经在下面发布了我的代码,非常感谢任何可以帮助我解决所遇到问题的技巧或命中。

The current output is:
Say something: hey
Size of char: 8
Size of s: 8
Size of t: 8
Doubling copy...
Original: hey
Double copy: hey
Counter: 8


所需的输出是:

Say something: hey
Size of char: 8
Size of s: 8
Size of t: 8
Doubling copy...
Original: hey
Double copy: heyhey (I would like this line to print double the word the user entered as input)
Counter: 8


码:

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
     int scale_value = 2;
     int counter = 0;

    printf("Say something: ");
    char* s = GetString();

    if (s == NULL)
    {
        return 1;
    }

    string t = malloc((strlen(s) * scale_value + 1)* sizeof(char));

    if (t == NULL)
    {
        free(s);
        return 1;
    }

    printf("Size of char: %lu\n", sizeof(char*));
    printf("Size of s: %lu\n", sizeof(s));
    printf("Size of t: %lu\n", sizeof(t));

    for(int j = 0; j < scale_value; j++)
    {
        for (int i = 0, n = strlen(s); i<=n; i++)
        {
                t[counter] = s[i];
                counter++;
        }
    }

    printf("Doubling copy...\n");

    if (strlen(t)>0)
    {
        printf("Original: %s\n", s);
        printf("Double copy: %s\n", t);
        printf("Counter: %d\n", counter);
    }
}

最佳答案

这是因为您复制了终止空字符scale_value次而不是一次,并且第一个终止空字符将终止字符串。此问题不仅会过早终止字符串,还会导致超出范围的访问(缓冲区溢出)。

试试这个,而不是复制部分:

for(int j = 0; j < scale_value; j++)
{
    /* change <= to < to exclude the terminating null-character from what is copied */
    for (int i = 0, n = strlen(s); i<n; i++)
    {
            t[counter] = s[i];
            counter++;
    }
}
/* terminate the string */
t[counter++] = '\0';


另请注意,%lu不是正确的格式说明符,不能打印sizeof类型为size_t的返回内容。使用%zu是正确的。
使用不正确的格式说明符将调用未定义的行为。

关于c - 将用户条目的两倍存储在C中的动态指针中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38033796/

10-12 17:32
查看更多