Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a string using a pointer

Tags:

c

string

pointers

Here's a program I wrote to copy a string constant.

When the program is run it crashes. Why is this happening ?

#include <stdio.h>

char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char c;
char *l;

main(){
   while((c = *alpha++)!='\0')
       *l++ = *alpha;
   printf("%s\n",l);
}
like image 503
Arabeka Avatar asked Sep 21 '13 23:09

Arabeka


People also ask

How do I copy a string to another string?

Copying one string to another - strcpy strcpy can be used to copy one string to another. Remember that C strings are character arrays. You must pass character array, or pointer to character array to this function where string will be copied. The destination character array is the first parameter to strcpy .

How do you copy a string in C ++?

You can simply copy string objects in C++ using = assignment operator.

Can a pointer point to a string?

A pointer to string in C can be used to point to the base address of the string array, and its value can be dereferenced to get the value of the string. To get the value of the string array is iterated using a while loop until a null character is encountered.


3 Answers

To copy strings in C, you can use strcpy. Here is an example:

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

const char * my_str = "Content";
char * my_copy;
my_copy = malloc(sizeof(char) * (strlen(my_str) + 1));
strcpy(my_copy,my_str);

If you want to avoid accidental buffer overflows, use strncpy instead of strcpy. For example:

const char * my_str = "Content";
const size_t len_my_str = strlen(my_str) + 1;
char * my_copy = malloc(len_my_str);
strncpy(my_copy, my_str, len_my_str);
like image 186
Vitor Villar Avatar answered Sep 28 '22 18:09

Vitor Villar


To perform such manual copy:

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

int main()
{
    char* orig_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char* ptr = orig_str;

    // Memory layout for orig_str:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // |A|B|C|D|E|F|G|H|I|J|K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z |\0|  --> data
    // ------------------------------------------------------------------------

    int orig_str_size = 0;
    char* bkup_copy = NULL;

    // Count the number of characters in the original string
    while (*ptr++ != '\0')
        orig_str_size++;        

    printf("Size of the original string: %d\n", orig_str_size);

    /* Dynamically allocate space for the backup copy */ 

    // Why orig_str_size plus 1? We add +1 to account for the mandatory 
    // '\0' at the end of the string.
    bkup_copy = (char*) malloc((orig_str_size+1) * sizeof(char));

    // Place the '\0' character at the end of the backup string.
    bkup_copy[orig_str_size] = '\0'; 

    // Current memory layout for bkup_copy:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // | | | | | | | | | | |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |\0|  --> data
    // ------------------------------------------------------------------------

    /* Finally, copy the characters from one string to the other */ 

    // Remember to reset the helper pointer so it points to the beginning 
    // of the original string!
    ptr = &orig_str[0]; 
    int idx = 0;
    while (*ptr != '\0')
        bkup_copy[idx++] = *ptr++;

    printf("Original String: %s\n", orig_str);   
    printf("Backup String: %s\n", bkup_copy);

    return 0;
}
like image 21
karlphillip Avatar answered Sep 28 '22 19:09

karlphillip


You need to allocate space for l. Currently it is pointing to a random spot in memory, and if you try to write to that spot, the operating system is likely to shut down (AKA crash) your application. If you want your code to work as is, then assign some space for l with malloc() or create l as an character array with enough space to hold "ABCDEFGHIJKLMNOPQRSTUVWXYZ" plus the NULL terminator.

See http://cslibrary.stanford.edu/106/ for a primer on pointers.

like image 31
lreeder Avatar answered Sep 28 '22 19:09

lreeder