C / C ++ questions on pointers (double pointers)

So, some time has passed since I took courses in c and C ++, and I'm curious to point with pointers (I'm going to use the new keyword in my examples, I even thought that I know that malloc is way C) . I always remember how my teacher always forced us to use a pointer, she would never take tasks with arrays, she proved to us that in assembly language fewer commands were needed when you used pointers, and not arrays used. I want to continue this good practice, but I seem to be struggling to use pointers, particularly dual scanners.

Suppose I want to create a word bank without using the C ++ string data type, 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 large enough for the entire bank. But I'm not sure how to do this. I think this is something like this?

wordBank = new char*[wordCount];

Now I need to allocate space separately for the size of each word, which I'm still not sure about 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];
}

, , , - . , , , , , . , , , . , . , , . , .

+4
2

:

wordBank = malloc(wordCount * sizeof(char *));

:

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);

. . std::string std::vector<string> . , mallocs frees, NULL-.

+8

:

wordBank = new char*[wordCount];

: wordCount char*

for(int i = 0; i < wordCount; i++)
{
   wordLength = getWordLength(fileName, i); // some function to get word length of each...
   //... word in the bank
   wordBank[i] = new char[wordLength];
}

(@angdev), (char *) .

os , , , ... :

  • malloc() --- > free()
  • new --- > use delete`
  • new [] --- > delete [] `

, , :

char *myPointer=0;

fillIt(myPointer);

... , fillIt() , myPointer , :

void fillIt(char * & p) { ... }

:

void fillIt(char ** p) { ... }

char *myPointer=0;

fillIt(&myPointer);
+1

Source: https://habr.com/ru/post/1534581/


All Articles