So its been a while since I took courses on c and c++ and I'm curious on c pointers (im going to use the new keyword in my examples even thought I know malloc is the C way). I always recall my teacher always forcing us to use pointer, she would never take assignments with arrays, she proved to us that there are less commands needed in assembly language when you used pointers rather then used arrays. I want to continue this good practice but I seem to be struggling to use pointers, specifically double pounter.
Lets say I want to create a word bank without using the c++ string datatype and I have a double pointer of type char.
int main()
{
string fileName = "file.txt";
char** wordBank = null;
int wordCount = countWords(fileName); //somefunction to get word count
}
Now I need to allocate a memory space big enough for the entire bank But im unsure on how to do this I believe it is somthing like this?
wordBank = new char*[wordCount];
now I need to allocate space specifilly for the size of each word, which i am still unsure aobut.
for(int i = 0; i < wordCount; i++)
{
wordLength = getWordLength(fileName, i); // some function to get word length of each...
//... word in the bank
(*wordBank) = new char[wordLength];
}
Okay the last part I'm confused about is passing double pointers through functions. lets say I have a function that lets me manipulate a an entire word, lets say I want to just pass the word, what would I pass through the function call and what would the function definition have. And lets say I want to pass the entire bank and a number that will move the pointer, what would I pass through the function call and what would the function definition have. Sorry for all the questions usually If I try to answer these things by myself by writing short programs but I'm having difficulty just getting it to compile. I appreciate the responses I receive.
To allocate the bank:
wordBank = malloc(wordCount * sizeof(char *));
To allocate individual words:
char *addWord(char **wordBank, size_t idx, char *word) {
wordBank[idx] = malloc(strlen(word) + 1);
// this is how you pass a word
strcpy(wordBank[idx], word);
return wordBank[idx];
}
// how you pass the wordBank:
addWord(wordBand, index, someWord);
But having more instructions in the assembly is not necessarily bad. A constant overhead is generally not a problem in programming. I would use std::string
and std::vector<string>
and spend my time on real problems. At least not on debugging mallocs and frees, assigning and testing NULL pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With