从函数返回时字符串更改的值

时间:2014-03-08 04:46:01

标签: c

我正在编写一个函数来删除文件路径的最后一段,但是我没有从我的函数中获取正确的字符串。我给函数输入sample/four.txt/one.txt"作为示例参数,我希望得到sample/four.txt。我在自己的机器上尝试过代码,getOldPath总是返回sample/f。在getOldPath函数内,curPathsample/four.txt。退出并将其分配到主newPath后,newPathsample/f。但是,当我在朋友的机器上运行程序时,他得到了预期的sample/four.txt。是什么导致了这个问题,我该如何解决?这是我正在使用的代码:

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


char *getOldPath(char *curPath)
{
    // Loop to find the count of characters

    int count;
    count = 0;

    int end;
    end = strlen(curPath);
    char tempChar;
    tempChar = curPath[end-1];

    while(tempChar != '/')
    {
            count++;
            end--;
            printf("End is: %i\n",end);
            tempChar = curPath[end];
    }


    char temp[256];
    int numChar;
    numChar = strlen(curPath) - count;
    strncpy(temp,curPath,numChar);
    curPath = temp;

    printf("The path is: %s\n",curPath);

    return curPath;
}


int main(int argc, char **argv)
{
    char *path = "sample/four.txt/one.txt";
    char *newPath = getOldPath(path);

    printf("Do we get the new path back: %s\n",newPath);

}

2 个答案:

答案 0 :(得分:3)

您正在返回指向对象的指针 - temp - 具有自动存储持续时间。这意味着temp仅在调用该函数的生命周期中存在。函数返回后使用它是未定义的行为,会产生不稳定的结果。

如果您希望它持续超出函数的末尾,您可以使用malloc或完全重构您的代码以使用调用者提供的内存。例如,替换可以是:

char *temp = malloc(256);
/* The caller must remember to free this. */

答案 1 :(得分:1)

您正在返回temp地址,该地址是函数中的局部变量,因此无法正常工作。修改了函数以包含输入字符串中的截断路径,并使用了strrchr()函数。检查 - 它可能对您有用。

void getOldPath(char *curPath)
{
    char *ptr;

    ptr = strrchr(curPath,'/');
    if(ptr != NULL)
    {  
        *ptr = '\0';      
    }

    printf("The path is: %s\n",curPath);
}
相关问题