Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying elements from one character array to another

I wanted to transfer elements from a string to another string, and hence wrote the following program. Initially, I thought that the for loop should execute till the NULL character (including it i.e) has been copied. But in this code, the for loop terminates if a NULL character has been found (i.e, not yet copied), but its still able to display the string in which the elements have been copied. How is this possible, if there is no NULL character in the first place?

#include<stdio.h>
#include<stdlib.h>

int main()
{
    char temp[100], str[100];
    fgets(str, 100, stdin);
    int i;
    for(i = 0; str[i]!='\0'; i++)
    {
        temp[i] = str[i];
    }
    puts(temp);
    return 0;
}
like image 856
Ranjan Srinivas Avatar asked Feb 20 '16 12:02

Ranjan Srinivas


People also ask

How do I copy one character array into another?

Using the inbuilt function strcpy() from string. h header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.

How do you assign a character array to another character array?

To copy String1 char array to String2 char array, you cannot simply assign the whole array to it, it has to be copied one character at a time within a loop, or use a string copy function in the standard library.

How do I copy a character to another character?

The C library function char *strncpy(char *dest, const char *src, size_t n) copies up to n characters from the string pointed to, by src to dest. In a case where the length of src is less than that of n, the remainder of dest will be padded with null bytes.

How do I copy a character array to another in C++?

Using c_str() with strcpy() A way to do this is to copy the contents of the string to the char array. This can be done with the help of the c_str() and strcpy() functions of library cstring.


2 Answers

The void puts(const char *) function relies on size_t strlen(const char *) and output of this function is undefined when there is no null terminator in the passed argument (see this answer). So in your case the strlen inside puts probably found a 0 value 'next to' your array in memory resulting in a proper behavior of puts, however that need not always be the case as it's undefined.

like image 131
maciekjanusz Avatar answered Sep 23 '22 03:09

maciekjanusz


Here is the input and output on my computer:

0
0
絯忐`

Process returned 0 (0x0)   execution time : 1.863 s
Press any key to continue.

See the garbage "絯忐`"? This is undefined behavior. Your program works well because you're (un)lucky.

Again, undefined behaviors don't deserve much discussion.

like image 21
nalzok Avatar answered Sep 23 '22 03:09

nalzok