Hi, I'm using Expat to parse XML, and I have an array of attributes for an element. I need to be able to loop through them all, and get their values, I don't know the array size, and it's a multidimensional array, so I couldn't do

int count = sizeof(array)/sizeof(char);

Please help.....

The array looks like this:

char **atts

.

At some point do you allocate memory to the array? Keep track of the sizes you used. When filling the array, is it filled completely, or does the data end at some lesser point? Keep count of how many elements read in.

I don't do the allocating.. Expat does.

XMLCALL startElement(void *userData, const char *name, const char **atts)

Once I define that function, It calls it with all of the parameters filled in for me so I can use them when it finds a new element.

In general, there's only four ways to know the dimensions.
1 they are stored globally, where your function can see them
2 they are passed explicitly as parameters to the function
3 they are in the array itself, typically as the first elements
4 some data value marks the end of row size and the last row

#1 and #4 are not my choices of methods to use. Overall, I like #2 best.

I found this:

while (*atts) {
    printf(" %s='%s'", atts[0], atts[1]);
    atts += 2;
  }

It works, but I have no idea what it's doing.

I found this:

while (*atts) {
    printf(" %s='%s'", atts[0], atts[1]);
    atts += 2;
  }

It works, but I have no idea what it's doing.

You found it where? Define "it works" and under what circumstances? I know nothing about Expat, but there are an awful lot of programs one could write where that code would result in a run-time error.

atts is the pointer to a dynamically allocated array of pointers.
*atts is a pointer to array of char
atts[0] should be the same as *atts, at the first access of the array.

printf( "%s", atts[0] ) displays the string starting at first row of the array, stopping when a zero byte (NULL terminator) is encountered.

HEY - you never said the data represented strings! That's important to know.

The while loop ends when atts is pointing to a byte that is zero value. Are you guaranteed that there will be at least one more allocated row, that is set to NULL?

This article has been dead for over six months. Start a new discussion instead.