这是在c中从一个字符指针复制到另一个字符指针的有效方法吗?

问题描述 投票:1回答:1

这是在c- *char_ptr2++=*char_ptr1++中从一个字符指针复制到另一个字符指针的有效方法吗?我无法运行该程序,我认为从一个字符指针复制到另一个字符指针时出错。

完整代码-

#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;
} 
c string pointers
1个回答
2
投票

必须分配C中的内存。有两种基本类型:堆栈或自动内存,以及堆或malloc内存。堆栈被称为“自动”,因为一旦离开该块,它将自动为您释放。 heap要求您手动分配和释放内存。

#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);
}

执行此操作的标准功能是strcpy。请注意确保分配了足够的内存,strcpy不会为您检查。

#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);
}

并且POSIX函数strdup将为您处理分配和复制。

strdup
© www.soinside.com 2019 - 2024. All rights reserved.