简体   繁体   English

在C中使用strcpy函数,不知道长度

[英]Using strcpy function in C, without knowing the length

Im trying to write a simple function that get name and return it after adding an extension to it. 我试图编写一个简单的函数来获取名称,并在添加扩展名后返回它。 for example, if i have the char pointer to "abcd" the function should return "abcd.as" 例如,如果我有指向“ abcd”的字符指针,则函数应返回“ abcd.as”

I tried to write this function that get char pointer and return a pointer to a new char after adding the extension. 我尝试编写此函数以获取char指针,并在添加扩展名后返回指向新char的指针。 But is not working does someone know why? 但是有人不知道为什么不工作吗?

char* AddFileExtension(char* FileName)
{
    char* FixFileName=NULL;
    char* Extension = ".as";
    strcpy(FixFileName, FileName);
    strcat(FixFileName, Extension);
    return FixFileName;
}

You have to allocate memory for FixFileName : 您必须为FixFileName分配内存:

char* Extension = ".as";
char* FixFileName = malloc(strlen(FileName) + strlen(Extension) + 1);

Don't forget to free() the memory when you're done with it. 完成后,不要忘记free()内存。 For obvious reasons, this has to be done outside the function. 出于明显的原因,必须在功能之外进行此操作。

you have to allocate memory for FixFileName and the size of allocate memory should be the lenght of FileName + sizeof(".as") 您必须为FixFileName分配内存,并且分配内存的大小应为FileName + sizeof(".as")的长度

Note: the sizeof will count the null character of ".sa" string so no need to add 1 for the null charachter of string FixFileName 注: sizeof将计算的空字符".sa"字符串,所以没有必要添加1串的空charachter FixFileName

char* AddFileExtension(char* FileName)
{
#define EXTENSION_AS ".as"    
    char* FixFileName= malloc(strlen(FileName) + sizeof(EXTENSION_AS));

    sprintf(FixFileName, "%s%s", FileName, EXTENSION_AS);
    return FixFileName;
}

do not forget to free the allocated memory when it became useless in your program with free() 当使用free()在程序中使分配的内存变得无用时,不要忘记释放已分配的内存

char* AddFileExtension(char* FileName)
{
    char* FixFileName=NULL;
    char* Extension = ".as";
    FixFileName=(char *) malloc(strlen(FileName)+strlen(Extension)+1);
    strcpy(FixFileName, FileName);
    strcat(FixFileName, Extension);
    return FixFileName;
}

Try the above code. 试试上面的代码。 You have to free the memory once you are done 完成后必须释放内存

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM