C语言 从for循环中的缓冲区指针依次向数组指针中添加元素



如何通过c中的指针将字符串字符数组中的元素添加到另一个字符数组中? 下面我已经给出了代码,请纠正它并提出任何建议,因为我没有得到一个满意的答案,我只是想在'复制'数组从'缓冲区'数组相同的字符串只使用那里的指针?

char buffer[5] = "stop";    // Buffer character array
char copy[5];               // Copy character empty array
// Pointers
char *buffer_ptr, *copy_ptr;
buffer_ptr = buffer;
copy_ptr = copy;
int i;
for ( i = 0; i < 4; i++)
{
strncpy(copy_ptr, buffer_ptr, 1);   // Here I want to copy string from buffer_pointer to copy_ptr
buffer_ptr = buffer_ptr + 1;        // Here buffer_pointer pointer address is up by 1    
copy_ptr = copy_ptr + 1;            // Here copy_pointer pointer address is up by 1
}    
printf("%sn", copy);
return 0; 
}

看起来就像你在尝试发明一个标准代码中已经存在的字符串操作方法。你实际上是在使用"结构"函数。以下是我认为你正在尝试做的事情的简化版本。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buffer[5] = "stop";    // Buffer character array
char copy[5];               // Copy character empty array

strcpy(copy, buffer);

printf("%sn", copy);

return 0;
}

如果出于某种原因,您需要操作来自"缓冲区"的数据;将字符前的字符串放入"copy"字符串(例如大写或小写),你可以使用如下方法:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buffer[5] = "stop";    // Buffer character array
char copy[5];               // Copy character empty array
for (int i = 0; i < strlen(buffer); i++)
{
/* If needed, some processing could be done to the buffer character */
copy[i] = buffer[i];
}
printf("%sn", copy);

return 0;
}

我希望这能给你一些启发。

致意。

对于初学者,数组buffer包含5字符,包括字符串字元"stop"的终止零字符''

char buffer[5] = "stop";    // Buffer character array

如果你要一个字符一个字符地复制那么for循环的条件应该写成

for ( i = 0; i < 5; i++)
^^^^^

如果你要使用指针来复制数组中的字符串,那么变量i是多余的。

调用strncpy函数只复制一个字符看起来不自然。

例如,你可以这样写for循环

#include <stdio.h>
int main(void) 
{
char buffer[5] = "stop";    // Buffer character array
char copy[5];               // Copy character empty array
for ( char *buffer_ptr = buffer, *copy_ptr = copy; 
( *copy_ptr++ = *buffer_ptr++ ) != ''; );
printf("%sn", copy);
}

可以将for循环移动到单独的函数中,例如

#include <stdio.h>
char * string_copy( char *s1, const char *s2 )
{
for ( char *p = s1; *p++ = *s2++; );
return s1;
}
int main(void) 
{
char buffer[5] = "stop";    // Buffer character array
char copy[5];               // Copy character empty array
puts( string_copy( copy, buffer ) );
}

程序输出为

stop

最新更新