passing dynamic character arrays

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

Moderators: cheriff, TyRaNiD

Post Reply
iamjeff
Posts: 3
Joined: Thu Jul 20, 2006 8:00 am

passing dynamic character arrays

Post by iamjeff »

hi, im new here... this might be a simple question, but i don't know how to fix it.

i read data in from a file and store it in a buffer
now, im trying to extract data from that buffer and store it in another variable. here is my code:

Code: Select all

class Element
{

public: 
	int GetNodeSize() {return nodesize;}
	char * GetNodeElement() {return node;}
	
	void SetNodeSize(int size) {
		nodesize = size;
		node = new char [nodesize];
	}
		
	void SetNodeElement(char *temp) {
		node = temp;
	}
	
private:
	int nodesize;
	char *node;

};

Code: Select all

void parseBuffer(char *buffer, long lSize) {
	int x, y, loop;
	char *tempnode;
	for &#40;x = 0; x <= lSize; x++&#41; 
		if &#40;buffer&#91;x&#93; == '<'&#41; &#123;
			y=x;
			while &#40;buffer&#91;y&#93; != '>'&#41;
				y++;
			XML&#91;0&#93;.SetNodeSize&#40;&#40;y-x&#41;-1&#41;;
			tempnode = new char &#91;XML&#91;0&#93;.GetNodeSize&#40;&#41;&#93;;
			for &#40;loop = 0; loop < XML&#91;0&#93;.GetNodeSize&#40;&#41;; loop++&#41;
				tempnode&#91;loop&#93; = buffer&#91;&#40;x+1&#41;+loop&#93;;
			XML&#91;0&#93;.SetNodeElement&#40;tempnode&#41;;
			delete &#91;&#93; tempnode;
			break;
		&#125;
	printf&#40;"%s\n", XML&#91;0&#93;.GetNodeElement&#40;&#41;&#41;;
&#125;
XML[0].GetNodeSize() returns the correct value.
however, the printf statement returns garbage.

if i change the printf statement to print tempnode instead (and comment out "delete tempode"), it comes close... it prints out the string i want, plus a few trailing garbge characters.

i figure it has something to do with the way i pass it to SetNodeElement (or maybe the assignment), but ive been trying all sorts of things and cant figure it out. what am i doing wrong?
Tinnus
Posts: 67
Joined: Sat Jul 29, 2006 1:12 am

Post by Tinnus »

Code: Select all

void SetNodeElement&#40;char *temp&#41; &#123;
      node = temp;
   &#125;
That copies the pointer, not the string data. You should use something like strcpy or a for loop.

Also, for the printf not to print garbage, you should add a NULL character( '\0' ) at the end of your string when reading from the file.
Let's see what the PSP reserves... well, I'd say anything is better than Palm OS.
iamjeff
Posts: 3
Joined: Thu Jul 20, 2006 8:00 am

Post by iamjeff »

works perfectly, much thanks!
Post Reply