简体   繁体   English

向动态char数组添加反斜杠

[英]Adding a backslash to a dynamic char array

int main(int argc, char *argv[])
{
    char *arr;

    arr = (char*)malloc((strlen(argv[1]) + 1) * sizeof(char));//1 additional byte for the backslash.
    strcpy(arr, argv[1]);
    strcat(arr, '\\');

    return 0;
}

After this code I get Access violation reading error. 这段代码后,我得到Access violation reading错误。
Basically I'm just trying to append a backslash to a dynamic string that contains the first argument of the program. 基本上,我只是想将反斜杠附加到包含程序第一个参数的动态字符串中。

This is probably wrong: 这可能是错误的:

arr = (char*)malloc((strlen(argv[1]) + 1) * sizeof(char));

argv[1]+1 is the second argument, if exists. argv[1]+1是第二个参数(如果存在)。 You wanted: 你自找的:

arr = malloc(strlen(argv[1]) + 2);

I simplified this line a lot since sizeof(char) is 1 by definition and adding 2 instead of 1 as you would need additional byte for the nul terminator. 由于sizeof(char)根据定义为1并加上2而不是1 ,因此我简化了这一行,因为您需要为nul终止符增加字节。 Casting malloc is unnecessary . 强制转换malloc不必要的

strcat operates on strings. strcat对字符串进行操作。 '\\\\' is not a string. '\\\\'不是字符串。 It should be: 它应该是:

strcat(arr, "\\");

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

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