//Pointers on C programming practise 4.4
//this is my code
#include <stdio.h>
#include <string>
void copy_n ( char dst[], char src[], int n );
void copy_n ( char dst[], char src[], int n ){
int m = strlen(src);
if( m < n ){
int i;
for( i = 0; m + i < n; i++ ){
src[m + i] = '0';
}
}
for( int j = 0; j < n; j++ ){
dst[j] = src[j];
}
}
int main(void)
{
printf("Enter data:\n");
char first[10];
char second[] = "abcde";
int n = 10;
copy_n(first, second, n);
for( int i = 0; i < n; i++ )
{
printf("%c",first[i]);
}
return 0;
}
//this is my previous function code
void copy_n ( char dst[], char src[], int n ){
if( strlen( src ) < n ){
int i;
for( i = 0; strlen(src) + i < n - 1; i++ ){
src[strlen(src) + i] = '0'; //每次循环 src 数组的长度都增加 1 导致了不能实现题意函数功能
} //这种错误是致命的
}
for( int j = 0; j < n; j++ ){
dst[strlen(dst) + j] = src[j];
}
}
//the standard answer
</pre><pre class="cpp" name="code" snippet_file_name="blog_20150326_8_2280315" code_snippet_id="628142">void copy_n ( char dst[], char src[], int n ){
int dst_index, src_index;
src_index = 0;
for( dst_index = 0; dst_index < n; dst_index += 1 ){
dst[dst_index] = src[src_index];
if( src[src_index] != 0 )
src_index += 1;
}
}