首页 > 解决方案 > 您如何使用标头中的 strcat()连接两个指针指向的字符串?

问题描述

我正在尝试连接两个字符串以用作 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 使用尊重运算符是否正确?

标签: cstringpointersstrcat

解决方案


这里有 3 件事要解决:

  1. 您为 inputchar 分配了恰好 1 个字符的空间。因此,获取长度超过 0 个字符的字符串会弄乱程序的内存。为什么长于 0 个字符?因为gets在字符串的末尾写了一个终止的0字符。所以分配更多的东西,例如

    char *inputchar = (char*)malloc(256*sizeof(char));
    
  2. 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可能对你有好处。


推荐阅读