簡體   English   中英

如何從標題使用strcat() <string.h> 連接兩個指針指向的字符串?

[英]How do you use strcat() from the header <string.h> to concatenate two pointer-pointed strings?

我試圖將兩個字符串連接起來用作fopen()的路徑。 我有以下代碼:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>

void main() {
    char *inputchar = (char*)malloc(sizeof(char)), *absolutepath = (char*)malloc(sizeof(char));
    FILE *filepointer;

    gets(inputchar); //Name of the file that the user wants
    absolutepath = "D:\\Files\\";
    strcat(*inputchar, *absolutepath); //Error occurs here
    filepointer = fopen(*inputchar, "r"); //Do I need to use the deference operator?
    fclose(filepointer);
    free(inputchar);
    free(absolutepath);
}

strcat()發生錯誤。 那里發生了什么?

我必須在fopen()的inputchar中使用引用運算符對嗎?

這是3處要修復的問題:

  1. 您為輸入字符分配恰好1個字符的空間。 因此,使用大於0個字符的字符串會弄亂程序的內存。 為什么要長於0個字符? 因為gets在字符串的末尾寫入一個終止的0字符。 所以多分配一些東西,例如

     char *inputchar = (char*)malloc(256*sizeof(char)); 
  2. absolutepath = "D:\\\\Files\\\\"; "D:\\\\files\\\\" absolutepath = "D:\\\\Files\\\\"; "D:\\\\files\\\\"是字符串文字,其值由編譯器確定。 因此,您不需要使用malloc為該字符串分配空間。 您可以說:

     char *absolutepath = "D:\\\\Files\\\\"; 
  3. 調用strcat時,將指針值賦給它,而不是字符串的第一個字符。 所以你應該做

     strcat(inputchar, absolutepath); 

    代替

     strcat(*inputchar, *absolutepath); 

我建議閱讀一些初學者的C資源,例如, http//www.learn-c.org/en/Strings可能對您有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM