How do I properly use strcat for char array?

Carol Ward

I'm trying to concatenate another string onto arg[0].

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

int main() {

    char* arg[] = {
        "Hello",
        NULL,
        NULL,
        NULL
    };

    strcat(arg[0], " World");

}

This returns abort trap.

What am I doing wrong?

RobertS supports Monica Cellio

You are trying to rewrite a string literal with:

char* arg[] = { "Hello", ..... };    // "Hello" is a string literal, pointed to by "arg[0]".

strcat(arg[0], " World");       // Attempt to rewrite/modify a string literal.

which isn´t possible.

String literals are only available to read, but not to write. That´s what make them "literal".


If you wonder about why:

char* arg[] = { "Hello", ..... }; 

implies "Hello" as a string literal, You should read the answers to that question:

What is the difference between char s[] and char *s?


By the way, it would be even not possible (or at least get a segmentation fault at run-time) if you would do something like that:

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

int main() {

    char a[] = "Hello";  // 6 for holding "Hello" (5) + "\0" (1). 

    strcat(a, " World");   

}

because the array a needs to have 12 characters for concatenating both strings and using strcat(a, " World"); - "Hello" (5 characters) + " World" (6 characters) + \0 (1 character) but it only has 6 characters for holding "Hello" + \0. There is no memory space added to the array automagically when using strcat().

If you execute the program with these statements, you are writing beyond the bounds of the array which is Undefined Behavior and this will get you probably prompt a Segmentation Fault error.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related