Hirdetés

Új hozzászólás Aktív témák

  • Sk8erPeter

    nagyúr

    válasz shev7 #1390 üzenetére

    Akkor lehet, hogy valami fogalmi képzavar esete forog fenn nálam, vagy nem vágom,
    de az alábbi példaprogram jól szemlélteti a dinamikus memóriafoglalást, amire gondoltam, itt az eredeti tömbből egy új tömbbe gyűjti az eredeti tömbben szereplő, átlag alatti számokat, és pont akkora memóriát foglalunk le az új tömbnek, amennyire szükség van, nem többet, nem kevesebbet:

    #include <stdio.h>
    #include <stdlib.h>
    double *atlagalatt(double tomb[], int meret, int *ujmeret){
    double *ujtomb;
    int i, db, to;
    double szum, atlag;

    /* mi az atlag */
    szum=0;
    for (i=0; i<meret; ++i)
    szum+=tomb[i];
    atlag=szum/meret;

    /* hany olyan van */
    db=0;
    for (i=0; i<meret; ++i)
    if (tomb[i]<atlag)
    db++;

    /* foglalas es paranoia */
    ujtomb=(double*)malloc(db*sizeof(double));
    if (!ujtomb) {
    *ujmeret=0;
    return NULL;
    }

    /* masolas */
    to=0;
    for (i=0; i<meret; ++i)
    if (tomb[i]<atlag)
    ujtomb[to++]=tomb[i];
    *ujmeret=db;
    return ujtomb;
    }

    int main(){
    double eredeti[100];
    double *uj;
    int ujmeret;
    int i;

    for (i=0; i<100; ++i)
    eredeti[i]=rand()%100/10.0;

    uj=atlagalatt(eredeti, 100, &ujmeret);
    for (i=0; i<ujmeret; ++i)
    printf("%4.2g ", uj[i]);
    free(uj);
    }

    Szerk.: Forrás: [link]

    Sőt, ha már linkeltem, itt látható a 4-es feladatban a futásidőben történő memóriafoglalás:

    #include <stdio.h>
    #include <stdlib.h>

    char ** darabol(char *s,char *m,int *db){
    int n=0,i,last=0;
    char **p;
    // szavak számolása
    for(i=0;s[i]!=0;i++){
    int j;
    for(j=0; m[j]!=0 && s[i]!=m[j]; j++);
    if(m[j]!=0 && i!=last){
    n++;
    last=i+1;
    }
    }
    p=(char**)malloc(n*sizeof(char*));
    if(p==NULL)exit(-1);
    for(i=n=last=0;s[i]!=0;i++){
    int j;
    for(j=0; m[j]!=0 && s[i]!=m[j]; j++);
    if(m[j]!=0 && i!=last){
    p[n]=(char*)malloc(i-last+1);
    if(p[n]==NULL)exit(-1);
    for(j=last;j<i;j++)p[n][j-last]=s[j];
    p[n][j-last]=0;
    n++;
    last=i+1;
    }
    }
    *db=n;
    return p;
    }

    int main(int db,char ** par){
    FILE * fp;
    char sor[1025];
    int meret;
    if(db<3)return -1;
    fp=fopen(par[1],"rt");
    if(fp==NULL)return -1;
    while(fgets(sor,1025,fp)!=NULL){
    char **p=darabol(sor,par[2],&meret);
    while(meret--)free(p[meret]);
    free(p);
    }
    }

    [ Szerkesztve ]

    Sk8erPeter

Új hozzászólás Aktív témák