This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                6年前关闭。
            
                    
在C程序中,我采用2个命令行参数,并将它们作为单个参数连接到这样的函数中:

some_function(strcat(argv[1], argv[2]));


因此,例如,如果我传递arg1和arg2,则传递的结果是arg1arg2

然后,在函数内部,我需要将它们重新分为arg1和arg2。我试过像这样使用strtok()函数(用arg连接字符串):

source = strtok(arg, "\\");
destination = strtok(NULL, "\\");


但这似乎不起作用,因为连接的字符串arg1arg2存储在源中,而null存储在目标中。那么,如何获取它,以便源为arg1而目标为arg2?

最佳答案

解决上述问题的最简单方法是将参数复制到新数组中。

char args[strlen(argv[1]) + strlen(argv[2]) + 1];
sprintf(args, "%s%s", argv[1], argv[2]);


或者,更传统地:

char *args = malloc(strlen(argv[1]) + strlen(argv[2]) + 1);
sprintf(args, "%s%s", argv[1], argv[2]);
/* free args when you are through with it */


现在,argv[1]argv[2]仍然分开。

关于c - 在C中连接字符串,然后将其重新分离,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16288066/

10-11 22:07