如何拼接字符指针?C语言调用system()执行xcopy时参数拼接失败问题解决
Ah, I get it—you're tripping over a key difference between C and Java when it comes to string handling. Let's break this down and fix your code.
Your original code fails because C doesn't support string concatenation with the + operator like Java does. In Java, String objects have the + operator overloaded to combine strings seamlessly, but in C, when you write "xcopy "+source+destination, you're actually doing pointer arithmetic—not string joining. That expression calculates an invalid memory address, which is why system() can't execute the command properly.
Solution 1: Use snprintf (Recommended for Safety)
The safest way to build your command string is to use snprintf, which lets you write formatted text into a buffer while respecting its size to avoid overflow. Here's how to do it:
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char *source = "D:\\SOFTWARE\\Internet"; char *destination = " D:\\test /s /e /d /y"; // Calculate the total length needed for the command string size_t total_length = strlen("xcopy ") + strlen(source) + strlen(destination) + 1; // +1 accounts for the null terminator that ends every C string // Allocate memory dynamically for the command char *command = (char*)malloc(total_length); if (command == NULL) { perror("Failed to allocate memory"); return 1; } // Build the full xcopy command snprintf(command, total_length, "xcopy %s%s", source, destination); // Execute the command system(command); // Don't forget to free the allocated memory! free(command); return 0; }
Solution 2: Use a Fixed-Size Buffer (Simpler for Short Paths)
If you're confident your source and destination paths won't be excessively long, you can use a fixed-size character array instead of dynamic memory:
#include <stdio.h> #include <string.h> int main() { char *source = "D:\\SOFTWARE\\Internet"; char *destination = " D:\\test /s /e /d /y"; // Choose a buffer size large enough to hold your command (adjust as needed) char command[512]; // Build the command into the buffer snprintf(command, sizeof(command), "xcopy %s%s", source, destination); // Run the command system(command); return 0; }
Key Notes:
- Always prefer
snprintfoversprintf—snprintfprevents buffer overflow by limiting the number of characters written, which avoids crashes or potential security issues. - In C, strings are just arrays of characters terminated by a null byte (
\0). You can't "add" pointers together to combine strings; you have to manually copy or format them into a single buffer.
内容的提问来源于stack exchange,提问作者coder_hasib

