这是在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中的内存。有两种基本类型:堆栈或自动内存,以及堆或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