String concatenation. WITH

All code is below in C.

Both of the code snippets below are compiled, but the difference is that the second program crashes on startup.

One:

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

void main() {
    char *foo = "foo";
    char *bar = "bar";
    char *str[80];;
    strcpy (str, "TEXT ");
    strcat (str, foo);
    strcat (str, bar);
}

Two:

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

void main() {
    char *foo = "foo";
    char *bar = "bar";
    char *str="";
    strcpy (str, "TEXT ");
    strcat (str, foo);
    strcat (str, bar);
}

The difference is that in the first case the row size is indicated str, and the second is not. How to concatenate strings without directly specifying string size str?

+4
source share
7 answers

The difference is that in the first case, the size of str is specified as a string, and the second is not.

No. In the first program, the following statement

char *str[80];

defines stras an array of pointers 80for characters. You need an array of characters -

char str[80];

In the second program

char *str="";

str "", . - .

,

char *str="";

str . strcpy , , .

str "", . str strcpy, undefined, strcpy , . undefined , , - - - segfault ( ) . , undefined.

str?

, else strcpy , , undefined - . , . strcat undefined. , str.

+3

:

:

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

void main() {
    char *foo = "foo";
    char *bar = "bar";
    char str[80];
    strcpy (str, "TEXT ");
    strcat (str, foo);
    strcat (str, bar);
}

:

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

void main() {
    char *foo = "foo";
    char *bar = "bar";
    char str[80]="";
    strcpy (str, "TEXT ");
    strcat (str, foo);
    strcat (str, bar);
}
+2
#include <stdio.h>
#include <string.h>

void main() {
    char *foo = "foo";
    char *bar = "bar";
    char *str=NULL;
    size_t strSize = strlen(foo)+strlen(bar)+strlen("TEXT ")+1;

    str=malloc(strSize);
    if(NULL==str)
       {
       fprintf(stderr, "malloc() failed.\n");
       goto CLEANUP;
       }

    strcpy (str, "TEXT ");
    strcat (str, foo);
    strcat (str, bar);

CLEANUP

    if(str)
       free(str);        
    }
+1
size_t len1 = strlen(first);
size_t len2 = strlen(second);

char * s = malloc(len1 + len2 + 2);
memcpy(s, first, len1);
s[len1] = ' ';
memcpy(s + len1 + 1, second, len2 + 1); // includes terminating null

?

+1

char * str = "; 1 , null . char * str =" 0123456789 ", 11 , 10 " 0123456789", 11- . , str, . , .

+1

, undefined , . char *str[80]; - , (strcpy, strcat) , char *. str char str[80];

, char *str=""; , . :

 char* str = malloc(80);
 strcpy(str,"");
 strcpy (str, "TEXT ");
 strcat (str, foo);
 strcat (str, bar);
+1

. , 80 char *str = new char[10]; . malloc .

Here are some links that may help you.

http://www.cplusplus.com/reference/cstdlib/malloc/ http://www.cplusplus.com/reference/cstdlib/calloc/

+1
source

Source: https://habr.com/ru/post/1537172/


All Articles