开发者

Assigning char value in one array to char value in another array

Sounds easy, but I've got a bug and I'm not sure what's causing it?

nopunccount = 0;
char *ra = new char[sizeof(npa)];
while (nopunccount <= strlen(npa)) {
    ra[nopunccount] = npa[strlen(npa) - nopunccount]; 
    nopunccount++;
}

ra never gets a value into it and I have verified 开发者_开发问答that npa has char values to provide within the nopunccount range.

Any help is appreciated // :)


nopunccountstarts as 0, so in the first iteration of the loop the character assigned to ra[0] is npa[strlen(npa)]. This is the terminating '\0' of that string. So the resulting string in ra starts with a '\0' and is therefore considered to be ending at that first byte by the usual string functions.


What does the declaration of npa look like? If it is a pointer, sizeof(npa) will be the size of a pointer, rather than the allocated size. If these are zero-terminated strings (also known as "C strings"), then use strlen, not sizeof. If these aren't strings, you need to track how much you allocated in a separate variable.

I have some other critiques of this code, possibly unrelated to your problem.

while (nopunccount <= strlen(npa)) {

strlen is an O(n) operation. This code will traverse the string npa in every loop iteration. It's best to only compute the length once.

   ra[nopunccount] = npa[strlen(npa) - nopunccount];

Same problem here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜