Prob bei Speicherallocation



  • Hab ein Problem mit der Speicherallocation für eine Struktur. Immer wenn ich bis zum Block mit der Allocation komme bricht das Programm ab.

    Hier ist der Code:

    typedef struct
    {
    char sccMonthBeg[3]; //erst mal die Deklaration der Struktur
    char sccYearBeg[5];
    char sccMonthEnd[3];
    char sccYearEnd[5];
    char sccText[lengthmax+1];
    }scItem;

    scItem *pscItemSchools[5]; //Array aus fünf Pointern vom Typ der Struktur

    pscItemSchools[iCount]= (scItem )malloc(1sizeof(scItem));
    if (pscItemSchools[iCount]==NULL)
    {
    printf("Fehler bei der Speicherallocation! Programm wird abgebrochen\n");
    exit(1);
    } // Speicherallocation.

    Bin schon am verzweifeln. Würde mich über einen Tipp freuen.

    Im voraus schon mal danke. Cu



  • Hallo!

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct
    {
    	char sccMonthBeg[3];
    	char sccYearBeg[5];
    	char sccMonthEnd[3];
    	char sccYearEnd[5];
    	char sccText[5];
    }scItem;
    
    int main(void)
    {
    	unsigned iCount;
    	scItem** pscItemSchools;
    
    	pscItemSchools = (scItem**)malloc(5*sizeof(scItem*));
    	if(pscItemSchools==NULL)
    	{
    		exit(1);
    	}
    	for(iCount=0;iCount<5;iCount++)
    	{
    		pscItemSchools[iCount] = (scItem*)malloc(1*sizeof(scItem));
    
    		if (pscItemSchools[iCount]==NULL)
    		{
    			exit(2);
    		}
    	}
    	printf("Hat geklappt!");
    
    	/* Wichtig: Du musst den Speicher in umgekehrter Reihenfolger wieder freigeben! */
    	for(iCount=0;iCount<5;iCount++)
    	{
    		free(pscItemSchools[iCount]);
    	}
    	free(pscItemSchools);
    
    	return 0;
    }
    

    Ich hoffe das hilft dir bei deinem Problem...

    Mfg, Matthias



  • Wie greif ich dann auf eine der Strukturvariablen zu? z.B. möchte ich in eine Strukturvariable eine Zeichenkette kopieren?



  • Lazarus1 schrieb:

    Wie greif ich dann auf eine der Strukturvariablen zu? z.B. möchte ich in eine Strukturvariable eine Zeichenkette kopieren?

    strcpy(pscItemSchools[index]->sccMonthBeg, "11");



  • Da du hier nicht im C-Subforum bist, frag ich mich warum du keine STL-strings
    verwendest. 😕

    mfg JJ



  • Na würde ich sicher wenn ich wüsste was das ist. Hab so ein paar Bücher hier über C aber da steht nichts drin über diese Strings



  • Ach ja thx nochmal für die tips


Anmelden zum Antworten