1

Is this a valid method to copy from one character pointer to other in c- *char_ptr2++=*char_ptr1++? I am not able to run the program, i think there is an error while copying from one character pointer to other.

Full Code-

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

int main() 
{ 
    char* char_ptr1;
    char* char_ptr2;
    *char_ptr1="this is a string";
    while(*char_ptr1)
        *char_ptr2++=*char_ptr1++;
    printf("Entered string is %s",char_ptr2);
    return 0;
} 
Roshan
  • 43
  • 5
  • 1
    No, this invokes *undefined behavior* - you didn't allocate any memory for `char_ptr2` – UnholySheep Jun 12 '20 at 22:05
  • You haven't allocated any memory to copy it into. – alani Jun 12 '20 at 22:05
  • 1
    `*char_ptr1="this is a string";` also shouldn't compile. `*char_ptr1` is a single `char`, it cannot hold a string – UnholySheep Jun 12 '20 at 22:05
  • Will initializing it to NULL help? – Roshan Jun 12 '20 at 22:06
  • No, you need to allocate memory, e.g.: by using `malloc`. You cannot just write into random addresses and assume things will work out – UnholySheep Jun 12 '20 at 22:07
  • @Roshan No, you need to allocate memory. Either define it as an array and make sure that you don't overrun it (use `strncpy`), or dynamically allocate with `malloc`. – alani Jun 12 '20 at 22:07
  • 1
    Even if it *did* work, you can't print the string like that. For one thing, it has no NUL terminator, for another `char_ptr2` is now pointing to the wrong place. – Weather Vane Jun 12 '20 at 22:08
  • After allocating it memory. Can i use the above method to copy from ```char_ptr1```? – Roshan Jun 12 '20 at 22:10
  • As @WeatherVane has just pointed out, you are not copying the NUL terminator. You will also need a temporary pointer variable for your loop so that you still keep a copy of the pointer to the start of the string, if you are going to actually use it for anything. – alani Jun 12 '20 at 22:11

1 Answers1

2

Memory in C must be allocated. There's two basic types: stack or automatic memory, and heap or malloc memory. Stack is called "automatic" because it will be automatically freed for you once you leave the block. heap requires that you manually allocate and free the memory.

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

int main() 
{ 
    // A character array.
    char char_ptr1[] = "this is a string";

    // Allocate space for the string and its null byte.
    // sizeof(char_ptr1) only works to get the length on
    // char[]. On a *char it will return the size of the
    // pointer, not the length of the string.
    char* char_ptr2 = malloc(sizeof(char_ptr1));

    // We need copies of the pointers to iterate, else
    // we'll lose their original positions.
    char *src = char_ptr1;  // Arrays are read-only. The array will become a pointer.
    char *dest = char_ptr2;
    while(*src != '\0')
        *dest++ = *src++;
    // Don't forget the terminating null byte.
    *dest = '\0';

    printf("%s\n", char_ptr2);

    // All memory will be freed when the program exits, but it's good
    // practice to match every malloc with a free.
    free(char_ptr2);
}

The standard function to do this is strcpy. Be careful to be sure you've allocated sufficient memory, strcpy will not check for you.

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

int main() 
{ 
    char char_ptr1[] = "this is a string";
    char* char_ptr2 = malloc(sizeof(char_ptr1));

    strcpy(char_ptr2, char_ptr1);

    printf("%s\n", char_ptr2);

    free(char_ptr2);
}

And the POSIX function strdup will handle both the allocation and copying for you.

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

int main() 
{ 
    char char_ptr1[] = "this is a string";
    char* char_ptr2 = strdup(char_ptr1);

    printf("%s\n", char_ptr2);

    free(char_ptr2);
}
Schwern
  • 153,029
  • 25
  • 195
  • 336
  • 1
    Allocated memory is not generally a [heap](https://en.wikipedia.org/wiki/Heap_%28data_structure%29), and there is no reason to describe it as such. At least with automatic memory, it is frequently (but not always) a stack, and there is a close association between the semantics required of automatic memory by the C standard and the behavior of a stack. But for allocated memory, there is no reason to mislead students by describing it as a heap. And there are not just two “types” of memory (storage durations); the C standard also specifies static and thread. – Eric Postpischil Jun 12 '20 at 23:32
  • @EricPostpischil You are technically correct! But this isn't a comprehensive review of C memory management. The goal is to help someone struggling with basic memory and string operations, they will not understand these nuances. I mention "heap" with `malloc` because [it is a common term they may have heard](https://study.cs50.net/malloc); they may not even know what a heap is. I understand there are more types of memory, that is why I said "basic types", and they are not relevant to the answer. – Schwern Jun 13 '20 at 02:41