3

I am trying to copy from a character array to character pointer. My code:

char str[] = "Hello World";
char *result = (char *)malloc(strlen(str)+1);
int index=0;
while(index <= strlen(str))
{
  *result = str[index];
  result++;
  index++;
}

This above code is not working and below code is working

char str[] = "Hello World";
char *result = (char *)malloc(strlen(str)+1);
int index=0;
while(index <= strlen(str))
{
  result[index] = str[index];
  index++;
}

Can anyone explain this behavior?

14
  • 4
    The first code is working, well almost anyway. The problem with it is that you modify the pointer so after the loop it will not point to the original location. If you make another pointer variable and before the loop make it too point to result then you will see that it will work. Commented Jan 22, 2015 at 11:23
  • 1
    You should use index <= strlen(str) – 'less or equal' rather than 'less than'. Commented Jan 22, 2015 at 11:25
  • 2
    Note that it's inefficient to call strlen repeatedly. It doesn't change, after all. Commented Jan 22, 2015 at 11:26
  • 1
    As pointed out by CiaPan, you forgot to copy the trailing \0; your resulting string is an unterminated string. This might lead to undefined behavior in subsequent code. Commented Jan 22, 2015 at 11:26
  • 1
    @CiaPan: <= is correct here, but you should explain why. (You need the copy the last \0 as well) Commented Jan 22, 2015 at 11:27

6 Answers 6

9

we simply use the strcpy function to copy the array into the pointer.

     char str[] = "Hello World";
     char *result = (char *)malloc(strlen(str)+1);
     strcpy(result,str);
Sign up to request clarification or add additional context in comments.

1 Comment

I want to implement strcpy() in my own way.
8

In your first snippet you modify the pointer in the loop, so after the loop it will no longer point to the same location returned by the malloc call.

Look at it this way, after the call to malloc the pointer and the memory look like this:

result
|
v
+---+---+---+---+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+---+---+

After the first iteration of the loop it will look like this:

    result
    |
    v
+---+---+---+---+---+---+---+---+---+---+---+---+
| H |   |   |   |   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+---+---+

And after the loop is done it will look like this

                                                 result
                                                 |
                                                 v
+---+---+---+---+---+---+---+---+---+---+---+----+
| H | e | l | l | o |   | W | o | r | l | d | \0 |
+---+---+---+---+---+---+---+---+---+---+---+----+

The copying is made, but the pointer no longer points to the original position.

[Note: Before the copying, the memory allocated by malloc will not be "empty" or initialized in any way, I just show it like that here for simplicity's sake.]

1 Comment

maybe we should add that using the result pointer this way OP won't even be able to free it anymore; that's why most of the cases I prefer array notation, it's also more readable
4

Try this code.. Use strcpy() function.

char str[] = "Hello World";
char *result = (char *)malloc(strlen(str)+1);
strcpy(result,str);

Comments

2

Already you allocate a memory for that pointer, so you can simply use the strcpy() function to copy the characters

 strcpy(result,str);

str copied to result.

4 Comments

its better to use strncpy instead of strcpy i guess
@sudhi - If we want to copy specified length of characters then we can use strncpy(). Here the whole array copied to the pointer, so we can simply use the strcpy() function.
@Bhuvanesh-You are correct , both strcpy and strncpy solves this purpose . But strncpy will provide more control, i mean to say sometime strcpy causes stack corruption (this can happen if we try to copy more than intended data from source to destination).
@sudhir That's not true in this case because the output buffer was allocated with malloc(strlen(str)+1) Therefore, strcpy is guaranteed to work correctly and not overflow the buffer. If a fixed size output buffer was being used, and the length of the input string was unknown, then strncpy would be a better choice.
1

In my opinion, there is no practical reason to modify your pointers (like you do in the first snippet) when you can just add an offset (like you do in the second snippet). It just makes the code a little bit harder to get right.

For the first snippet, try saving the original result like this:

char *result = ...
char *start = result;

And after the loop, try printing start, instead of result. It should point to the newly copied string, like you expect.

Comments

1

Your first code snippet copied the string perfectly , but in this process you moved allocated character pointer. If it has to work save its initial value in some temporary pointer

char str[] = "Hello World";
char *result = (char *)malloc(strlen(str)+1);
char *tmp = result;
int index=0;
while(index <= strlen(str))
{
  *result = str[index];
  result++;
  index++;
}
printf("%s\n", tmp);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.