views:

128

answers:

2

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 // :)

+2  A: 

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.

asveikau
Thanks, good points :)
Spanky
+4  A: 

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.

sth
Groovy, didn't know that you can't have a null value mid string, but that makes perfect sense. Thanks :)
Spanky
A null-terminated string can't have a null in the middle of the string by definition, because a null ends the string...
Frederik Slijkerman