Search code examples
cstringpointersstrcat

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


I'm trying to concatenate two strings to be used as a path for fopen(). I have the following code:

#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);
}

Error occurs at strcat(). What happened there?

And is it correct that I have to use deference operator for inputchar at fopen()?


Solution

  • Here are 3 things to fix:

    1. You allocate space for exactly 1 character for inputchar. Thus getting a string longer than 0 characters with gets messes up your program's memory. Why longer than 0 character? Because gets writes a terminating 0 character at the end of the string. So allocate something more, e.g.

      char *inputchar = (char*)malloc(256*sizeof(char));
      
    2. absolutepath = "D:\\Files\\"; "D:\\files\\" is a string literal whose value is determined by the compiler. So you don't need to allocate space for that string with malloc. You can just say:

      char *absolutepath = "D:\\Files\\";
      
    3. When calling strcat, you give the pointer values to it, rather than the first characters of your strings. So you should do

      strcat(inputchar, absolutepath);
      

      instead of

      strcat(*inputchar, *absolutepath);
      

    I would recommend reading some beginners C resource, e.g. this http://www.learn-c.org/en/Strings could be good for you.