dynamicly sized arrays

Discuss the development of new homebrew software, tools and libraries.

Moderators: cheriff, TyRaNiD

Post Reply
Masamune
Posts: 6
Joined: Thu Jan 12, 2006 5:37 am

dynamicly sized arrays

Post by Masamune »

I recently started trying to program some psp stuff and I'm having trouble with a few things. Most importantly is dynamicly sized arrays. What I normaly do in C++ is something like this:

Code: Select all

int size = 10;
char test[];
test = new char[size];
I know you can't do that in C code which is what the samples seem to be writen in. If I rename the file with .cpp it looks like it uses psp-g++ but I learned C++ using Visual Studio 6.0 so I'm not used to make files and such. It gives me an error saying that there is no size defined for test. I actually haven't programmed in C++ for a while, so maybe I'm just doing it wrong all together. Can I just not do somthing like that or is there a C equivilant?
jsgf
Posts: 254
Joined: Tue Jul 12, 2005 11:02 am
Contact:

Post by jsgf »

Code: Select all

char test[size];
should work. "size" needs to be pretty small, because it gets allocated on the stack, and implicitly freed when the function returns (ie, its like any other local). If you want to allocate it on the heap, use

Code: Select all

char *test = malloc(size); /* C */
char *test = new char[size]; // C++
Masamune
Posts: 6
Joined: Thu Jan 12, 2006 5:37 am

Post by Masamune »

Code: Select all

psp-g++ -I. -I/usr/local/pspdev/psp/sdk/include -O2 -G0 -Wall -I. -I/usr/local/p
spdev/psp/sdk/include -O2 -G0 -Wall -fno-exceptions -fno-rtti   -c -o main.o mai
n.cpp
main.cpp: In function 'int main()':
main.cpp:66: warning: unused variable 'test1'
psp-gcc -I. -I/usr/local/pspdev/psp/sdk/include -O2 -G0 -Wall  -L. -L/usr/local/
pspdev/psp/sdk/lib   main.o  -lpspdebug -lpspdisplay -lpspge -lpspctrl -lpspsdk
-lc -lpspnet -lpspnet_inet -lpspnet_apctl -lpspnet_resolver -lpsputility -lpspus
er -lpspkernel -o kptest.elf
main.o: In function `main':
main.cpp:(.text+0xd8): undefined reference to `operator new[](unsigned int)'
collect2: ld returned 1 exit status
make: *** [kptest.elf] Error 1
That's the error I get when I use this in code:

Code: Select all

int size = 10;
char *test1 = new char[size];
I'm using the kprintf example from the samples, I just rename it to main.cpp and add the above lines to the main function. Do I need to change the make file at all for C++?

Edit: It compiles fine as C if I use malloc(). I'd much rather get the C++ way working, but this works for now. Thanks for the help :)
TyRaNiD
Posts: 907
Joined: Sun Jan 18, 2004 12:23 am

Post by TyRaNiD »

The reason for this is you are using gcc to link, you need to add -lstdc++ to your libraries in order to use C++. As you are using the pspsdk makefiles then in your apps makefile add the line LIBS=-lstdc++ and it _should_ work ;)
Masamune
Posts: 6
Joined: Thu Jan 12, 2006 5:37 am

Post by Masamune »

Sweet! that worked, thanks.
Post Reply