Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcpy using pointers

Tags:

c

I'm trying to write strcpy on my own using pointers and I get an error during runtime.

void str_cpy(char **destination, const char *source) {
//    char *s1 = *destination;

   while (*source != '\0') {
      **destination++ = *source++; //Get an error here
   }
   **destination = '\0';
}

I call the function as follows:

char *str = NULL;
str_cpy(&str, "String");

Is it not OK?

Thanks!

like image 249
oridahan Avatar asked Nov 19 '12 19:11

oridahan


People also ask

Can you use strcpy with pointers?

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 I use strcpy?

Parameter of strcpy() in C In C to use the strcpy() function, we must pass two strings of the same length as a parameter of the function. The two strings will be the source string and the destination string so that the content of the source string can be copied to the destination string.

Can you call strcpy with a string literal?

strcpy() — Copy Strings The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string. No length checking is performed. You should not use a literal string for a string1 value, although string2 may be a literal string.

What is strcpy in C with example?

strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string. h header file and in C++ it is present in cstring header file. Syntax: char* strcpy(char* dest, const char* src);


2 Answers

No, it's not okay. Why? Because str is a NULL pointer. It's pointing to nothing. When you try to write values into it, where will they go? It's not pointing to any allocated memory!

You first have to allocate memory for str. You can do:

char *str = malloc(strlen("String") + 1); // + 1 for the '\0' character at the end of C-style strings

Or you can do:

char str[256]; // make str large enough to hold 256 chars. Note that this is not as safe as the above version!

Also, destination should be a single pointer, not a double pointer. Well, it's not technically wrong to use a double pointer, it's just unnecessary.

Optionally, you can allocate the memory in the str_cpy function, like so:

void str_cpy(char **destination, const char *source) {
    *destination = malloc(strlen(source) + 1);
    // ... continue as normal
like image 135
Cornstalks Avatar answered Sep 26 '22 07:09

Cornstalks


For simplicity's sake, this can be done in one line in a function.

void mystrcpy(char *dest, const char *src) {
  while (*dest++ = *src++);
}

This being said, you do need to allocate memory for dest beforehand using malloc or just simply by having a character array like char dest[256].

like image 38
squiguy Avatar answered Sep 25 '22 07:09

squiguy