C语言 如何使用指针复制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18938779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy a string using a pointer
提问by Arabeka
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++)!='#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);
')
*l++ = *alpha;
printf("%s\n",l);
}
回答by Vitor Villar
To copy strings in C, you can use strcpy. Here is an example:
要在 C 中复制字符串,您可以使用 strcpy。下面是一个例子:
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);
If you want to avoid accidental buffer overflows, use strncpyinstead of strcpy. For example:
如果您想避免意外的缓冲区溢出,请使用strncpy代替strcpy。例如:
#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 |char *str = "some string thats not malloc'd";
char *tmp = NULL;
int i = 0;
for (i = 0; i < 6; i++) {
tmp = &str[i];
}
printf("%s\n", tmp);
| --> data
// ------------------------------------------------------------------------
int orig_str_size = 0;
char* bkup_copy = NULL;
// Count the number of characters in the original string
while (*ptr++ != 'char *str = "some stupid string";
char *tmp, *ptr = NULL;
ptr = str;
while (*str) { ++str; }
int len = str - ptr;
int i = 0;
for (i = len; i > 11; i--) {
tmp = &ptr[i];
}
printf("%s\n", tmp);
')
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
// '#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 256
int main(void) {
char *original, *copy, *start; //three character pointers
original = malloc(sizeof(char) * MAX_LENGTH); //assigning memory for strings is good practice
gets(original); //get original string from input
copy = malloc(sizeof(char) * (strlen(original)+1)); //+1 for char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *l = alpha;
start = copy;
while((*original)!='const char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char *l = alpha;
')
*copy++ = *original++;
*copy = '#include<stdio.h>
void cpy(char *src,char *des)
{
while(*(des++) = *(src++));
*des = '##代码##';
}
int main()
{
char src[100];
char des[100];
gets(src);
cpy(src,des);
printf("%s",des);
}
';
copy = start;
printf("The copy of input string is \"%s\".",copy);
return 0;
}
' at the end of the string.
bkup_copy = (char*) malloc((orig_str_size+1) * sizeof(char));
// Place the '##代码##' character at the end of the backup string.
bkup_copy[orig_str_size] = '##代码##';
// 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
// ------------------------------------------------------------------------
// | | | | | | | | | | | | | | | | | | | | | | | | | | |##代码##| --> 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 != '##代码##')
bkup_copy[idx++] = *ptr++;
printf("Original String: %s\n", orig_str);
printf("Backup String: %s\n", bkup_copy);
return 0;
}
回答by karlphillip
To perform such manual copy:
要执行此类手动复制:
##代码##回答by lreeder
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 lwith malloc()or create las an character array with enough space to hold "ABCDEFGHIJKLMNOPQRSTUVWXYZ"plus the NULL terminator.
您需要为l. 目前它指向内存中的一个随机位置,如果您尝试写入该位置,操作系统可能会关闭(也称为崩溃)您的应用程序。如果您希望您的代码按原样工作,则为lwith分配一些空间malloc()或创建l一个字符数组,该数组具有足够的空间来容纳"ABCDEFGHIJKLMNOPQRSTUVWXYZ"加上 NULL 终止符。
See http://cslibrary.stanford.edu/106/for a primer on pointers.
有关指针的入门,请参阅http://cslibrary.stanford.edu/106/。
回答by lreeder
Copy a string "constant/literal/pointer"
##代码##复制字符串“常量/文字/指针”
Reversed
##代码##反转
tmp = &blah[i]can be interchanged with tmp = &(*(blah + i)).
tmp = &blah[i]可以与tmp = &(*(blah + i)).
回答by Shail
回答by Pankaj Kumar Thapa
You can directly do the below code:
您可以直接执行以下代码:
##代码##If your code was below:
如果您的代码如下:
##代码##:)
:)
回答by Shadab Eqbal
cpy function will take two char pointers and the src pointer will point to the initial character of src(char array) defined in the main function, and same as the des pointer will point to the initial location of des(char array) defined in the main function and the while loop value of the src pointer will assign the value to des pointer and increment the pointer to the next element, this will happen until while loop encountered with null and comes out of the loop and des pointer will simply assigned null after taking all the values.
cpy 函数将采用两个 char 指针,src 指针将指向 main 函数中定义的 src(char array) 的初始字符,而 des 指针将指向 main 函数中定义的 des(char array) 的初始位置。 main 函数和 src 指针的 while 循环值会将值分配给 des 指针并将指针增加到下一个元素,这将发生,直到 while 循环遇到 null 并退出循环并且 des 指针将在之后简单地分配 null取所有值。
##代码##Output: Image
输出:图像

