Hi all. I am having a problem with dynamic array allocation. In my function of addNums, I was wondering if someone could tell me why it is reserving an array of 24 elements when I am telling it to reserve something else. For example, if the strlen of n1 = 3 and the strlen of n2 = 2, adding 2 to that should give 7, but it still allocates for 24. Maybe I missed something in my text, but my variables of num1 and num2 work correctly. Any ideas? Any and all help is greatly appreciated. Thank you!
cout << strlen(ans) << endl; It doues not return the size of allocated array. In fact it can return absolutely anything. It can even crash. strlen() requires that its argument was a null-terminated string as a precondition. Otherwise its behavior is undefined. As you never set terminating null anywhere, it reads random memory until it hits 0.
Line 86: You call strlen() on an uninitialized array. You allocate ans at line 86, but never move anything to it. C-strings are not initialized when dynamically allocated. strlen() is going to scan ans until it finds a terminaing null. ans contains random characters. It is pure chance that you got 24.
You have a memory leak in your program. You never delete the three character arrays that you allocate. Every time though the loop at lines 19-29, you allocating new instances of the three arrays without ever deleting them.
I can't really figure out the results you're getting, but...
line 74: surely you want n.length() + 1, not n.length() - 1? Because it looks like you do index beyond your array limits in lines 75 and 76, but maybe I'm missing something.
line 84: you create an uninitialised array, so strlen() will do what? If you're lucky and it's all zeroes you'll get zero, otherwise some random length or even a crash. I magine you want to do strncpy and strncat before proceeding from there.
Thank you for all of your responses. I have been trying to review some concepts about pointers, as it was never something that really stuck with me. To explain what the program does, it adds two positive integers using dynamic arrays with the paper and pencil algorithm from grade school. In the addNumbers function, I was trying to create a dynamic array that would be large enough to hold the answer of the addition and wanted to make sure that it was correct before preceding to write the actual function itself. As for everything else, I was trying to use output statements to see the values of everything before proceeding to the next step. I assigned the value NULL to the ans array of the index that would be large enough to hold the result of the addition and everything now works as planned. Again, thank you for all of the help, as I'm sure I will have another post on pointers as I try to review some concepts about them.