Fundamental question with a pointer to C using 'strcpy'

Man, pointers keep bothering me. I thought I understood the concept. (Basically, you should use * ptr when you want to manipulate the actual memory stored in the location pointed to by ptr. You just use ptr if you want to move this pointer by doing things like ptr ++ or ptr--.) So if so, if you use an asterisk to manage the files that the pointer points to, how it works:

char *MallocAndCopy( char *line ) {

    char *pointer;
    if ( (pointer = malloc( strlen(line)+1 )) == NULL ) {
        printf( "Out of memory!!!  Goodbye!\n" );
        exit( 0 );
    }
    strcpy( pointer, line );

    return pointer;
}

malloc returns a pointer, so I understand why the "pointer" in the if condition does not use an asterisk. However, in the strcpy function, it sends the contents of the string to the contents of the pointer. Must not be:

strcpy( *pointer, *line);

????? , strcpy?

+3
11

C . , .

strcpy char ( ) char '\0', .

, malloc, , , strlen(line)+1, ( ).

+6

char* strcpy(char *destination, const char *source) strcpy. . pointer , line.

strcpy source destination , source destination, \0 (NULL) , source, , ( ) .

*pointer, char , .

+4

strcpy

char * strcpy ( char * destination, const char * source );

char *, , char *. , , . * * ", " - .

+1

scrcpy , , . . , . - , .

+1

strpcy().

char *strcpy(
   char *strDestination,
   const char *strSource 
);

. , . char.

+1

* strcpy.

* [0].

strlen strcpy , , , .

pointer char *, *pointer char, .

+1

*pointer, , ( , pointer). strcpy . , strcpy , , .

, *line, strcpy .

, :

. . - C, - μ.

+1

, *pointer *line strcpy. , pointer , strlen(line)+1 . , , strcpy , strlen(line) , line , pointer. *pointer *line, strcpy char, strlen(line)-1. , strcpy.

0

strcpy . line pointer. , . .

-, , , ( ), . , , . C strcpy.

, . ( ) strcpy, , . .

, strcpy, . - . strcpy " , line , pointer". , .

0

strcpy :

char * strcpy(char * dst, char* src) 
{
    int i = 0 ;
    for (;dst[i]=source[i++];);
    return dst ;
}

\ 0 (NULL) - , for.

0
source

Your function is basically consistent strdup. A function is defined on many platforms if you cannot define this method:

char * my_strdup(const char* s)
{
  size_t len = strlen(s);
  char *r = malloc(len+1);
  return r ? memcpy(r, s, len+1) : NULL;
}

memcpy is usually faster than strcpy for longer strings.

0
source

Source: https://habr.com/ru/post/1769389/


All Articles