How to add a char/int to an char array in C?

后端 未结 5 877
感情败类
感情败类 2020-12-14 02:58

How can I add \'.\' to the char Array := \"Hello World\" in C, so I get a char Array: \"Hello World.\" The Question seems simple but I\'m struggling.

Tried the follo

5条回答
  •  星月不相逢
    2020-12-14 03:14

    In C/C++ a string is an array of char terminated with a NULL byte ('\0');

    1. Your string str has not been initialized.
    2. You must concatenate strings and you are trying to concatenate a single char (without the null byte so it's not a string) to a string.

    The code should look like this:

    char str[1024] = "Hello World"; //this will add all characters and a NULL byte to the array
    char tmp[2] = "."; //this is a string with the dot 
    strcat(str, tmp);  //here you concatenate the two strings
    

    Note that you can assign a string literal to an array only during its declaration.
    For example the following code is not permitted:

    char str[1024];
    str = "Hello World"; //FORBIDDEN
    

    and should be replaced with

    char str[1024];
    strcpy(str, "Hello World"); //here you copy "Hello World" inside the src array 
    

提交回复
热议问题