简单的char指针发送到功能不起作用

时间:2012-12-25 09:52:36

标签: c string pointers char

我正在尝试编写3个函数: 第一个:“read_comp”初始化一个char指针并为其指定返回的函数“readAndRemove”。 readAndRemove从用户读取行并删除字符串前的任何空格,并返回指向字符串的指针,而不包含开头的空格。 然后“read_comp”打印由“readAndRemove”得到的字符串 - 没有空格的字符串。

最后一个功能 - 我遇到问题的那个...... 功能“findComplex”: 我正在尝试这个函数做的只是获取char指针并打印函数得到的字符串。

void read_comp(void)
{
    char *str = readAndRemove();
    printf("%s\n",str);
    findComplex(&str);
}

-------------

char * readAndRemove() /**function to read rest of input and remove first space**/
{
    char tempChar[30];
    fgets(tempChar,30,stdin);
    char* ptr = strtok(tempChar, " ");
    return ptr;
}

--------------
void findComplex(char* str)
{
    printf("in findComplex:%s\n",str);

}

(对不起,如果开始是无关紧要的,但我想也许我做的一切都有问题......)

所以我试图解决并改变一些事情: 改变这个:定义char * str;作为全球参数 和chanege功能:

void read_comp(void)
{
    *str = readAndRemove();
    printf("%s\n",str);
    findComplex(str);
}

char * readAndRemove() /**function to read rest of input and remove first space**/
{
    char tempChar[30];
    fgets(tempChar,30,stdin);
    char* ptr = strtok(tempChar, " ");
    return ptr;
}


void findComplex(char* str)
{
    printf("%s\n",str);
    printf("in findComplex:%s\n",str);

}

2 个答案:

答案 0 :(得分:0)

str函数中的变量read_comp已经是指针。使用address-of运算符&使得它成为指向指针的指针(即类型char **)。在调用之前,请确保findComplex函数是原型,并且不要使用address-of运算符。

但是你有一个更大的问题,那就是readAndRemove函数返回一个指向局部变量的指针。请记住,局部变量存储在堆栈中,并且当函数返回时,堆栈空间被回收以供其他函数调用重用。改为在read_comp函数中创建数组,并将其大小与readAndRemove函数一起传递。

答案 1 :(得分:0)

如果你在你的编译器中启用警告(我在说“请执行此操作!”),你会得到一个警告,说“返回指向本地变量的指针”或类似的东西:

char * readAndRemove() /**function to read rest of input and remove first space**/
{
    char tempChar[30];
    fgets(tempChar,30,stdin);
    char* ptr = strtok(tempChar, " ");
    return ptr;
}

你必须不返回指向局部变量的指针,因为当你从这个函数返回时,tempchar使用的空间(ptr将指向)将被下一个函数重用 - 并且很可能下一个函数会写一些东西除了你的字符串进入这个记忆。

我建议,解决方法是将tempchar移动到read_comp() [1],并将字符串传递给readAndRemove

[1]请尝试决定是使用“camelcase”还是“_”名称。您的功能应该是read_and_removeread_compreadAndRemovereadComp。我差点写错了,因为我希望在这两个函数中找到相同的样式 - 当你后来尝试改变某些东西时,这种事情会让你发疯。