为什么我的char数组指针不打印?

时间:2017-11-21 01:56:27

标签: c linux pointers printf

我被分配了在C中编写生产者/消费者程序的任务。生产者流程方法如下所示,并试图从用户输入的字符串(producerString)中捕获元音。我无法测试是否正确创建vowelString

我确定该方法运行完成,但在执行第二个printf时没有打印任何内容。它与我如何打印指针有关吗?

char * Producer(char producerString[])          //PRODUCER FUNCTION
{
        char *vowelString = (char *) malloc(sizeof(char) * 100);
        vowelString = "";                       //String used to append vowels to

        printf("In Producer with producerString = %s\n", producerString);

        for (int i = 0; producerString[i] != '\0'; i++)
        {
                if (producerString[i] == 'a' || producerString[i] == 'e' || producerString[i] == 'i' || producerString[i] == 'o' || producerString[i] == 'u' || producerString[i] == 'y')
                {
                        int len = strlen(vowelString);
                        vowelString[len] = i;
                        vowelString[len + 1] = '\0';
                }
                else if (producerString[i] == 'p')
                {
                        exit(0);
                }
        }

        printf("In Producer with vowelString = %s\n", vowelString);

        return vowelString;                     //Return vowels string
}

我也尝试在以下方式从Producer方法返回后在Main方法中打印它:

char *producedString = Producer(inString);

printf("The produced string: %s\n", producedString);

这也行不通,但我认为这是同一问题的结果。

提前感谢您提供任何帮助,并感谢任何其他提示。

1 个答案:

答案 0 :(得分:2)

vowelString = "";不是初始化动态分配字符串的方式。这是指向指向静态文字字符串的指针,它不再指向malloc的内存。文字字符串不可修改,因此当您写入vowelString[i]时,您会导致未定义的行为。

将该行更改为:

vowelString[0] = '\0';

另外,

vowelString[len] = i;

应该是:

vowelString[len] = producerString[i];

但是,不是每次通过循环调用strlen(),而是可以在函数开头简单地初始化len0,并在每次附加元音时递增它。

char * Producer(char producerString[])          //PRODUCER FUNCTION
{
    char *vowelString = (char *) malloc(sizeof(char) * 100);

    printf("In Producer with producerString = %s\n", producerString);

    int len = 0;
    for (int i = 0; producerString[i] != '\0'; i++)
    {
        if (producerString[i] == 'a' || producerString[i] == 'e' || producerString[i] == 'i' || producerString[i] == 'o' || producerString[i] == 'u')
        {
            vowelString[len++] = producerString[i];
        }
        else if (producerString[i] == 'p')
        {
            exit(0);
        }
    }
    vowelString[len] = '\0';

    printf("In Producer with vowelString = %s\n", vowelString);

    return vowelString;
}