如何使用 header <string.h> 中的 strcat() 连接两个 pointer-pointed 字符串?
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 个问题需要解决:
您为 inputchar 恰好分配了 space 1 个字符。因此,使用 gets 获取长度超过 0 个字符的字符串会扰乱程序的内存。为什么长于 0 个字符?因为 gets 在字符串末尾写入了一个终止字符 0。所以分配更多的东西,例如
char *inputchar = (char*)malloc(256*sizeof(char));
absolutepath = "D:\Files\"; "D:\files\"
是一个字符串文字,其值由编译器确定。因此,您不需要使用 malloc 为该字符串分配 space。你可以直接说:
char *absolutepath = "D:\Files\";
调用 strcat 时,您将指针值赋予它,而不是字符串的第一个字符。所以你应该做
strcat(inputchar, absolutepath);
而不是
strcat(*inputchar, *absolutepath);
我建议阅读一些初学者 C 资源,例如这个 http://www.learn-c.org/en/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 个问题需要解决:
您为 inputchar 恰好分配了 space 1 个字符。因此,使用 gets 获取长度超过 0 个字符的字符串会扰乱程序的内存。为什么长于 0 个字符?因为 gets 在字符串末尾写入了一个终止字符 0。所以分配更多的东西,例如
char *inputchar = (char*)malloc(256*sizeof(char));
absolutepath = "D:\Files\"; "D:\files\"
是一个字符串文字,其值由编译器确定。因此,您不需要使用 malloc 为该字符串分配 space。你可以直接说:char *absolutepath = "D:\Files\";
调用 strcat 时,您将指针值赋予它,而不是字符串的第一个字符。所以你应该做
strcat(inputchar, absolutepath);
而不是
strcat(*inputchar, *absolutepath);
我建议阅读一些初学者 C 资源,例如这个 http://www.learn-c.org/en/Strings 可能对你有好处。