我在Pointers on C 的错误点——1

//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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值