Tableau de listes chaînées C ++

J’ai donc pensé comprendre comment implémenter un tableau de pointeurs, mais mon compilateur dit le contraire = (. Toute aide serait appréciée, j’ai l’impression d’être proche mais je manque quelque chose de crucial.

1.) J’ai un struct appelé noeud déclaré :.

struct node { int num; node *next; } 

2.) J’ai déclaré un pointeur sur un tableau de pointeurs comme ceci:

 node **arrayOfPointers; 

3.) J’ai ensuite créé dynamicment le tableau de pointeurs en procédant comme suit:

 arrayOfPointers = new node*[arraySize]; 

D’après ce que je comprends, arrayOfPointers pointe maintenant vers un tableau de type de nœud x, x étant = à arraySize.

4.) Mais lorsque je veux accéder au cinquième élément de arrayOfPointers pour vérifier si son pointeur suivant est null, une erreur de segmentation se produit. En utilisant ceci:

 if (arrayOfPointers[5]->next == NULL) { cout << "I'm null" << endl; } 

Est-ce que quelqu’un sait pourquoi cela se passe? J’ai pu atsortingbuer une valeur à num en faisant: arrayOfPointers [5] -> num = 77;

Mais je ne comprends pas pourquoi la vérification du pointeur dans la structure provoque une erreur. En outre, pendant que nous y sums, quel serait le bon prototype pour passer arrayOfPointers dans une fonction? Est-ce toujours (node ​​** arrayOfPointers) ou est-ce autre chose comme (node ​​* & arrayOfPointers)?

Merci d’avance pour vos conseils ou astuces (haha)!

Code complet (mis à jour):

  /* * Functions related to separate chain hashing */ struct chainNode { int value; chainNode *next; }; chainNode* CreateNewChainNode (int keyValue) { chainNode *newNode; newNode = new (nothrow) chainNode; newNode->value = keyValue; newNode->next = NULL; return newNode; } void InitDynamicArrayList (int tableSize, chainNode **chainListArray) { // create dynamic array of pointers chainListArray = new (nothrow) chainNode*[tableSize]; // allocate each pointer in array for (int i=0; i next == NULL) { // insert new node to front of list, keeping next pointer still set to NULL chainListArray[hashAddress]->next = newNode; } else //else cell is pointing to a list of nodes already { // new node's next pointer will point to former front of linked list newNode->next = chainListArray[hashAddress]->next; // insert new node to front of list chainListArray[hashAddress]->next = newNode; } isInserted = true; cout << keyValue << " inserted into chainListArray at index " << hashAddress << endl; } return isInserted; } /* * Functions to fill array with random numbers for hashing */ void FillNumArray (int randomArray[]) { int i = 0; // counter for for loop int randomNum = 0; // randomly generated number for (i = 0; i < ARRAY_SIZE; i++) // do this for entire array { randomNum = GenerateRandomNum(); // get a random number while(!IsUniqueNum(randomNum, randomArray)) // loops until random number is unique { randomNum = GenerateRandomNum(); } randomArray[i] = randomNum; // insert random number into array } return; } int GenerateRandomNum () { int num = 0; // randomly generated number // generate random number between start and end ranges num = (rand() % END_RANGE) + START_RANGE; return num; } bool IsUniqueNum (int num, int randomArray[]) { bool isUnique = true; // indicates if number is unique and NOT in array int index = 0; // array index //loop until end of array or a zero is found //(since array elements were initialized to zero) while ((index < ARRAY_SIZE) && (!randomArray[index] == 0)) { // if a value in the array matches the num passed in, num is not unique if (randomArray[index] == num) { isUnique = false; } index++; // increment index counter } // end while return isUnique; } /* *main */ int main (int argc, char* argv[]) { int randomNums[ARRAY_SIZE] = {0}; // initialize array elements to 0 int hashTableSize = 0; // size of hash table to use chainNode **chainListArray; bool chainEntry = true; //testing chain hashing //initialize random seed srand((unsigned)time(NULL)); FillNumArray(randomNums); // fill randomNums array with random numbers //test print array for(int i = 0; i < ARRAY_SIZE; i++) { cout << randomNums[i] << endl; } //test chain hashing insert hashTableSize = 19; int hashAddress = 0; InitDynamicArrayList(hashTableSize, chainListArray); //try to hash into hash table for (int i = 0; i < ARRAY_SIZE; i++) { hashAddress = randomNums[i] % hashTableSize; chainEntry = SeparateChainInsert(randomNums[i], hashAddress, chainListArray); } system("pause"); return 0; } 

 arrayOfPointers = new node*[arraySize]; 

Cela retourne un tas de pointeurs non alloués. Votre tableau de niveau supérieur est correct, mais ses éléments sont toujours des pointeurs non initialisés. Par conséquent, procédez comme suit:

 ->next 

Vous invoquez un comportement indéfini. Vous déréférencez un pointeur non initialisé.

Vous avez alloué le tableau correctement, vous devez maintenant allouer chaque pointeur, c.-à-d.

 for(int i = 0; i < arraySize; ++i) { arrayOfPointers[i] = new node; } 

En passant, je réalise que vous apprenez, mais vous devriez comprendre que vous écrivez essentiellement C ici. En C ++, vous disposez d'une multitude de structures de données formidables qui gèrent l'allocation de mémoire (et, plus important encore, la désallocation) pour vous.

Votre code est bon, mais il concerne la façon dont vous avez déclaré votre InitDynamicArrayList. Une solution consiste à utiliser *** chainListArray ou la syntaxe plus semblable à C ++ pour utiliser des références comme celles-ci:

void InitDynamicArrayList (int tableSize, chainNode ** & chainListArray)