Adding space to char** element with strcat

309 views Asked by At

I got array like this:

char *family[3] ={"son", "father", "sister"};

and I want to align length of each element to the same size by using function strcat(son," "); but I get core dumped instead.

3

There are 3 answers

0
alk On BEST ANSWER

You cannot strcat() to a literal. And the latter is what the three "strings" are.

Literals are placed in read-only memory. They may not be overwritten, trying to do so causes a run-time error.

4
rmp On

I think you were trying to write something like this:

char family[3][MAX_LEN] = {"son", "father", "sister"};
strcat (family[i], "   ");

the differences on the definition of "family" with the original:

 char *family[3] ={"son", "father", "sister"};

is that here you have 3 pointers to 3 literal const strings which are read only. Thus you can not modify them with strcat.

Whereas on char s[3][L]={"a","b","c"} you allocate 3 char arrays of lenght L each in the stack and initialize them to 3 literals. So now you may modify them with strcat if L is big enough...

Also, you were using strcat() in a wrong way as @alk pointed out...

8
ryyker On

strcat() appends a copy of a source string to the end of a target string, including the terminating ASCII NUL byte. The initial character of the string to append overwrites the NUL byte at the end of the target string.

Therefore, you cannot set "son" as the target string because it is a literal string,

`strcat(family[0], " "); is what you are trying to do, but that will not work either because family[0] is set to "son\0\0\0\0" already and will cause buffer overflow.

Do this instead:

char *family[3] ={"son   ", "father", "sister"};//now family[0] is initialized with spaces to match length
                                                //(and strcat() statment is not needed)