You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拼接字符指针?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.

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 snprintf over sprintf—snprintf prevents 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:17:29