[SOLVED] Kleines Problem mit std::fill



  • Hallo, nach langer Abwesenheit melde ich mich zurück und hab auch gleich ein kleines Problemchen mitgebracht.

    Ich versuche ein kleines Programm zu scchreiben welches einen Irrgarten erstellt aber scheitere schon derzeit daran das 2D-Array, welches ich dafür erstellt habe, zu befüllen. Während 'memset' super funktioniert und keine Probleme macht (compilen ok, ausführen fehlerlos), will 'std:fill' irgendwie nicht (compilen ok, ausführen Programm bricht ab).

    So aber mal genug geschwafel hier ist mein kleines Code Beispiel.

    #include <cstdio>
    #include <cstdlib>
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <ctime>
    #include <algorithm>
    
    int main () // int argc, char* argv [])
    {
    	// creating maze array, for testing purposes of 10 width x 20 height
    	int playfield [10][20] = {};
    
    	// filling array with -1 for all cells
    	// memset(&playfield[0][0], -1, sizeof(playfield)); // funktioniert
    	std::fill(&playfield[0][0], &playfield[0][0] + sizeof(playfield), -1);
    
    	// initializing random generator, only needed once per runtime
    	srand (time (NULL));
    
    	for (int x = 0; x < 10; x++)
    	{
    		for (int y = 0; y < 20; y++)
    		{
    			std::cout << playfield [x][y] << " ";
    		}
    		std::cout << std::endl;
    	}
    
        return 0;
    }
    

    Vielen Dank schon mal im Voraus.



  • &playfield[0][0] + sizeof(playfield)/sizeof(playfield[0][0})
    


  • Warum doppelt initialisieren?

    int playfield [10][20] = { -1 };
    


  • Yuk! Mehrdimensionale Arrays... 🙂

    Du musst halt eins hinter das letzte Element greifen:

    std::fill(&playfield[0][0], &playfield[9][20], -1);
    // oder
    std::fill(&playfield[0][0], &playfield[10][0], -1);
    


  • Th69 schrieb:

    Warum doppelt initialisieren?

    int playfield [10][20] = { -1 };
    

    Weil das nur den allerersten Wert auf -1 setzt.

    @ Volkart: Danke, das war der Casus Knacktus 🙂



  • volkard schrieb:

    &playfield[0][0] + sizeof(playfield)/sizeof(playfield[0][0})
    

    Der Grund, dass das so geht ist, dass sizeof die Größe in Bytes zurückgibt. Deswegen klappt das mit dem memset auch.


Anmelden zum Antworten