Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 12
  1. #1

    [C] stringa di qualsiasi lunghezza

    ciao,
    ho una curiosità... come faccio a far inserire dall'utente una stringa di una lunghezza arbitraria ? cioè con un numero non specificato di caratteri... i vettori sono una entità statica in quanto bisogna già dall'inizio specificarne la "capienza", quindi come si può fare ? ho pensato di usare una malloc ma non so come...
    http://www.mangaitalia.net/

    questo è un cazzo metallizzato a quattro ruote e noi due siamo i coglioni che se lo portano dietro - da Bad Boys con Will Smith and Martin Lawrance di John Whoo

  2. #2
    Penso tu debba chiedere all'utente di inserire la dimensione della stringa per allocare un vettore dinamicamente:

    codice:
    cout << "Inserisci lunghezza stringa: ";
    cin >> len;
    char s = new char[len+1];  /* Prevediamo anche il carattere di fine stringa \0 */
    cout << "Inserisci stringa: ";
    gets(s);
    La luce è più veloce del suono,ecco xchè alcune persone sembrano brillanti fino a quando non parlano


  3. #3
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,304
    Non credo che si possa fare agevolmente. Il sistema più rapido è quello di allogaer un vettore con un numero "esagerato" di caratteri, tali da prevenire il 90% dei fault. Dipende comunque dal tipo di applicazione che stai scrivendo... se, ad esempio, devi chiedere il nome ad un utente, un vettore di 100 caratteri dovrebbe essere sifficienta al 99.9%.


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  4. #4
    Con un Malloc dovresti ugualmente conoscere la Dimensione...
    codice:
    #define DIM        30
    ...
    char *string;
    string = (char *) malloc (DIM * sizeof(char));
    L'unica e' crearti una funzione utilizzando un realloc...
    codice:
    ...
    char *string;
    char chr;
    unsigned int i;
    
    do {    
        chr = getch();
        string = (char *) realloc (string, (1+i)*sizeof(char));
        // Devi fare i controlli if (string == NULL) 
        string[i] = chr;
        i++;
    } while(chr != '\r' && chr != '\n');
    ...
    Non ti assicuro niente per la funzione.. Dagli un occhiata tu... Sono stanco e non ho voglia di pensare...:tongue:

    R e a l l o c
    codice:
    #include <stdlib.h>
    void *realloc(void *block, size_t size);
    Description
    Reallocates main memory.
    realloc attempts to shrink or expand the previously allocated block to size bytes. If size is zero, the memory block is freed and NULL is returned. The block argument points to a memory block previously obtained by calling malloc, calloc, or realloc. If block is a NULL pointer, realloc works just like malloc.
    realloc adjusts the size of the allocated block to size, copying the contents to a new location if necessary.

    Return Value
    realloc returns the address of the reallocated block, which can be different than the address of the original block.
    If the block cannot be reallocated, realloc returns NULL.
    If the value of size is 0, the memory block is freed and realloc returns NULL.
    M a l l o c
    codice:
    #include <stdlib.h> or #include<malloc.h>
    void *malloc(size_t size);
    Description
    malloc allocates a block of size bytes from the memory heap. It allows a program to allocate memory explicitly as it's needed, and in the exact amounts needed.
    Allocates main memory.The heap is used for dynamic allocation of variable-sized blocks of memory. Many data structures, for example, trees and lists, naturally employ heap memory allocation.
    For 16-bit programs, all the space between the end of the data segment and the top of the program stack is available for use in the small data models, except for a small margin immediately before the top of the stack. This margin is intended to allow the application some room to make the stack larger, in addition to a small amount needed by DOS.

    In the large data models, all the space beyond the program stack to the end of available memory is available for the heap.

    Return Value
    On success, malloc returns a pointer to the newly allocated block of memory. If not enough space exists for the new block, it returns NULL. The contents of the block are left unchanged. If the argument size == 0, malloc returns NULL.
    PoWered by:
    Gentoo 1.5.3 - Kernel 2.6.7
    Debian Sid - Kernel 2.6.7 - Bash 3.0
    Slackware current - Kernel 2.6.7

  5. #5
    mm quella di Knemo mi sembra più affidabile, più che altro al momento non devo fare nessun programma particolare, era solo per curiosità... voleva sapere come gestire la memoria dinamica con le stringhe senza sprecarla inutilmente... e quella con la malloc e realloc mi sembra più affidabile per il momento...
    http://www.mangaitalia.net/

    questo è un cazzo metallizzato a quattro ruote e noi due siamo i coglioni che se lo portano dietro - da Bad Boys con Will Smith and Martin Lawrance di John Whoo

  6. #6
    ciao,
    ho provato ma sono riusciuto solo ad utilizzare la malloc... per la realloc ho dei problemi...perchè me lo compila senza errori ma poi mi si crasha...
    http://www.mangaitalia.net/

    questo è un cazzo metallizzato a quattro ruote e noi due siamo i coglioni che se lo portano dietro - da Bad Boys con Will Smith and Martin Lawrance di John Whoo

  7. #7
    usare le liste???
    La stupidità umana e l'universo sono infinite.
    Della seconda non sono certo(Einstein)

    Gnu/Linux User

  8. #8
    è esagerato usare le liste per l'applicazion che devo fare...

    mi serve solo poter prendere in input una stringa lunga a piacere... senza sprecare la memoria...
    http://www.mangaitalia.net/

    questo è un cazzo metallizzato a quattro ruote e noi due siamo i coglioni che se lo portano dietro - da Bad Boys con Will Smith and Martin Lawrance di John Whoo

  9. #9

    Re: [C] stringa di qualsiasi lunghezza

    Originariamente inviato da rocco.g
    ciao,
    ho una curiosità... come faccio a far inserire dall'utente una stringa di una lunghezza arbitraria ? cioè con un numero non specificato di caratteri... i vettori sono una entità statica in quanto bisogna già dall'inizio specificarne la "capienza", quindi come si può fare ? ho pensato di usare una malloc ma non so come...
    riprendendo ciò che ha suggerito kNemo:
    codice:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        char *s;
        unsigned long i=0;
                   
        printf("inserisci una stringa:\n");
        
        if( ! (s = (char*) malloc(sizeof(char))) )
        {
            printf("\aimpossibile allocare la memoria\n");    
            return -1;
        }    
        
        while(1)
        {
            //s[i]=getchar();
            //if(s[i]=='\n') break;
            s[i]='A';
            if(i==999999) break;
            i++;
            if( ! (s = (char*) realloc(s, i+1)) )
            {
                printf("\aimpossibile allocare altra memoria\n");
                return -1;
            }
        }
        s[i]='\0';
        
        printf("la stringa inserita e\':\n%s\nsono stati allocati %d byte\n", s, ++i);
            
        free(s);
        
        system("pause");
        return 0;
    }
    ...Terrible warlords, good warlords, and an english song

  10. #10
    grazie... questo funziona anke meglio !


    posso solo chiedere qual è il significato di :

    if(i==999999) break; ?

    controlla se vengono immessi un tot di caratteri e se vengono superati non vengono presi in considerazione ?
    http://www.mangaitalia.net/

    questo è un cazzo metallizzato a quattro ruote e noi due siamo i coglioni che se lo portano dietro - da Bad Boys con Will Smith and Martin Lawrance di John Whoo

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.