converting int variable to Char using sprintf

Hi,

I am trying to create a char to send to sd.open as a filename using sprintf to insert the variable into a string.

This is as far as I have gotten but my arduino appears to reset when it is called, I assume it is causing a memory leak due to the char being unterminate. Can someone help me fix this?
My code is basically this (without the error checking and serial printing stuff)

void readnotes(int notes)
{
  char* filename;
  sprintf(filename, "notes%i.txt", notes);

openfile = SD.open(filename);

}

I have read the sprintf reference here - http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/ but I don't really have a programming background so I feel a little overwhelmed.

Thanks for any help,

David

This is as far as I have gotten but my arduino appears to reset when it is called, I assume it is causing a memory leak due to the char being unterminate. Can someone help me fix this?

filename is a pointer. What does it point to? That's right. Absolutely nothing. How can you expect to write data there?

Change filename from a pointer to an array of fixed (and large enough) size.

Thanks for the response, as I said I don't have a C background so your reference to pointer enabled me to find the information. I do wish you had not decided to point that out by asking a question you then answered yourself, it seemed a little rude to me.

Regardless, I do really appreciate your reply. I thought that the * meant that it was a char or variable length, not sure where I picked that up from.

I have now changed my code to include a fixed length char (char filename[13]:wink: which should be of sufficient size.

It is a bit of a learning curve from Javascript and HTML to this but this forum really helps.

Pain is ALWAYS the fastest teacher,,,Not the best but the Fastest... In My experience...

Bob

Well, regardless of the method, I appreciate being 'pointed' in the right direction.

sprintf(filename, "notes%i.txt", notes);

If this is going to be used to name a file, you might want to think about whether you want the file names to have the same length, or to sort alphabetically in any useful order. If so, you can format the numbers into a constant length string, for example this would add leading zeroes as necessary to pad it to three characters:

sprintf(filename, "notes%03i.txt", notes);

Thanks, that is a good point, it currently works to double digits in testing and I hope not to need more that 99 notes. But I will look into adding leading zeros.

They are created and read sequentially so they will never need ordering in a different way.

Currently I am just playing about with this stuff and I have no real use for the method. I may have to think about creating and storing an integer to keep track of the total number of notes so that each new note conforms to the sequence.