0

I have an SD card which I filled with 15 mp3 tracks and a text file that has 15 words and 15 tracks names. My question is regarding initializing the following

char* words[ ]
char* tracks [ ]

When I initialize them as [100] and [100], the listing of the dB doesn't work as I currently only have 15 tracks and words. I want code to have the ability to place 999.

So my question is: can I make both them variable arrays and how?

I tried leaving between the brackets empty and several other methods but they didn't work. So I wondering if anyone here have any other suggestions.

3
  • 1
    Use dynamic memory allocations, malloc and then realloc? Commented Dec 29, 2013 at 15:44
  • I tried using malloc but it didn't work, however will try to use realloc, thanks for your fast reply :D Commented Dec 29, 2013 at 15:50
  • Note char*words[] is an array of pointers! You will need buffer for string data also char[][]. As this is all dynamic, you better not use static arrays, but use some new keywords. Commented Dec 30, 2013 at 10:31

2 Answers 2

1

Arduino version of C/C++ has a great feature - VLA (variable length array, from C99) So, just use:

void process(int n)
{
    // Set up a buffer of n characters
    char b[n];
    // do the work
}

See: http://www.drdobbs.com/the-new-cwhy-variable-length-arrays/184401444

You need array of arrays? No problem (I hope). Pseudocode:

char* words[N]; // N - words
char word1[M] // M - word length
char word2[O] // O - second word length

words[0] = word1;
words[1] = word2;

Many answers suggest to use dynamic memory allocation - it works, but main drawback of such method - memory fragmentation. But remember - dynamic memory allocation is only method to return arrays from functions!

P.S. I can't verify code with compiler at the moment - please give me feedback if it doesn't work.

0

Arduino code is compiled as C++; you can use the new char[size] and delete[] operators.

1
  • I tried what still i didnt get anything but when i tried using: //words = (char** )calloc(track_size++,sizeof(char*)); //tracks = (char** )calloc(track_size++,sizeof(char*)); with delete []; it only outputs the last word and last track, i dont understand why?? Commented Dec 29, 2013 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.