尝试编写密文程序时遇到 "variable is uninitialized when used here" 错误

Encountering "variable is uninitialized when used here" error, when attempting to code a ciphertext program

我正在尝试制作一个密码程序,但我在密码函数的最后一步遇到了这个错误(如果我没有说清楚,真的很抱歉,这是我第一次asking/posting 这里有一个问题,关于我的 臃肿 代码)

代码如下:

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

string ptoc(string ptext);

//Declaration of validated key as global so that Caesar(ptoc) function can access it
long int ckey;

int main(int argc, string argv[])
{
    string *c;
    string ctext;
    string ptext;
    if (argc != 2)
{
    printf("Only enter the key\n");
    return 1;
}
else if (argc == 2)
{
    //Converting entered CL argument into integer
    c = &argv[2];
    long int key = strtol(argv[1], c, 10);
    if (key == 0) //
    {
        printf("Enter a valid key, a positive integer\n");
        return 1;
    }
    else // Assigning to another variable if valid
    {
        ckey = key;
    }
    printf("%ld\n", ckey);
}
ptext = get_string("Enter the plaintext: \n");
ctext = ptoc(ptext);
}

//Cipher function
string ptoc(string ptext)
{
string collect;
for (int i = 0, len = strlen(ptext); i < len; i++)
{

    char c = ptext[i];
    if (isalpha(c))
    {
        if (c == '.' || c == ',' || c == '!')
        {
            i++;
        }
        else if (isupper(c))
        {
            if (c >= 'A' && c <= 'Y')
            {
                 sprintf(collect, "%i", c + 1);
            }
            else if (c == 'Z')
            {
                sprintf(collect, "%i", c - 24);
            }
        }
        else if (islower(c))
        {
            if (c >= 'a' && c <= 'y')
            {
                sprintf(collect, "%i", c + 1);
            }
            else if (c == 'z')
            {
                sprintf(collect, "%i", c - 24);
            }
        }
    }
}
return collect;
}

编译器给我的错误是这样的:

Cae1.c:59:30: error: variable 'collect' is uninitialized when used here [-Werror,-Wuninitialized]
                     sprintf(collect, "%i", c + 1);
                             ^~~~~~~
Cae1.c:44:19: note: initialize the variable 'collect' to silence this warning
    string collect;
                  ^
                   = NULL

我不明白的是,当我在正确的范围内初始化变量 collect(它是一个字符串)时,为什么编译器说它未初始化?

对不起,又是一团糟。

这个声明

string collect;

等同于那个声明

char *collect;

由于类型定义

typedef char * string;

即此声明声明了一个具有不确定值的未初始​​化指针。并且这个指针用在这样的调用中

sprintf(collect, "%i", c + 1);

这会导致未定义的行为。

当您从函数 ptoc 返回此指针时,您需要动态分配指针指向的适当大小的内存。

类似

string collect = malloc( an_appropriate_size );