2015-10-11 1 views
-3

Je veux mettre des chaînes de différentes tailles dans un tableau 2D, représenté par char *array[size]; exemple pour différentes tailles de chaînes pourrait être: - "Hi", "Welcome";.Comment mettre des chaînes de différentes longueurs dans un pointeur, par exemple char * output [100]

Cela devrait entrer dans le tableau ci-dessus: Si le tableau est donné dans ce format: char array[][] je pourrais le faire, en utilisant le code ci-dessous .:

#include <stdio.h> 
#include <string.h> 

char array[][100]; 

int main() 
{  
    char buf[10]; 

    sprintf(buf,"%d", 12); 
    strcpy(array[0], buf); 
    sprintf(buf, "%s", "hello"); 
    strcpy(array[1], buf); 
    printf("%s %s", array[0], array[1]); 
} 

Mais même je suis incapable de le faire, Si le tableau est donné au format char *array[].

Toute aide sera très utile. Merci.

+2

Vous devez fournir une taille pour les deux dimensions. –

+0

sonne comme vous voulez 'char * ptrsToStrings [nRows] [nCols]'. Votre 'array [] [100]' fonctionne comme un tableau de chaînes, car une chaîne est déjà un tableau de 'char's. –

+0

Je suis désolé, mais comment donner la taille à la première dimension ici, son char * array [size]; –

Répondre

3

Comme vous l'avez codé en dur les deux chaînes de toute façon, vous pouvez déclarer un tableau de pointeurs comme ceci:

char *array[] = {"Hi", "Welcome"}; 

Ces chaînes littérales sont en lecture seule. Une approche plus exhaustive pourrait ressembler à ceci:

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

#define STRINGS 2 
#define MAXLEN 100 

int main(void) 
{  
    char buf[MAXLEN]; 
    char *array[STRINGS];      // array of string pointers 
    int i; 
    for (i=0; i<STRINGS; i++) { 
     printf("Enter string %d: ", i+1); 
     if (fgets(buf, MAXLEN, stdin) == NULL) 
      return 0;       // bad input 
     buf [ strcspn(buf, "\r\n") ] = 0;  // remove trailing newline etc 
     array[i] = malloc(strlen(buf)+1);  // only as much as needed 
     if (array[i] == NULL) 
      return 0;       // bad memory allocation 
     strcpy(array[i], buf); 
    } 

    // print the array 
    for (i=0; i<STRINGS; i++) { 
     printf("%s\n", array[i]); 
    } 

    // free the memory 
    for (i=0; i<STRINGS; i++) { 
     free(array[i]); 
    } 
    return 0; 
} 
+0

Oh oui, j'ai trouvé l'erreur. Je ne faisais pas de malloc avant strcpy, donc je recevais un défaut de segmentation. La déclaration fait un tableau de pointeurs sur les cordes dont je dois allouer la mémoire. Merci de m'avoir aidé :) –

2

Il existe deux types différents de structure de données appelée un « tableau à deux dimensions » en C. Les deux, grâce à la surcharge des opérateurs, ont des lignes adressées par table[i] et éléments abordés par table[i][j].

Un bloc contigu de mémoire qui est logiquement divisé en morceaux de ligne de taille est parfois appelé un tableau rectangulaire (parce que si vous Jeté les éléments comme une table, toutes les lignes seraient parfaitement alignées) et un tableau de pointeurs est parfois appelé un tableau ragged. Si vous voulez utiliser l'un d'entre eux, vous devez allouer de la mémoire pour chaque ligne. Voici un exemple de code qui mélange les deux.

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

#define ROWS 100U 
#define COLS 32U 

char rectangular_array[ROWS][COLS] = {'\0'}; 
char *ragged_array[ROWS] = {NULL}; 

int main(void) { 
    strncpy(rectangular_array[0], "hello,", COLS-1); 
    strncpy(rectangular_array[1], "world!", COLS-1); 
    /* I don't need to set the third string to "" or the final bytes to 
    * '\0' explicitly because I initialized the array to zeroes. 
    */ 

    size_t i = 0; 
    while(i < ROWS && rectangular_array[i][0]) { 
    const char* const s = &rectangular_array[i][0]; 
    const size_t m = strlen(s)+1; 
    char* const t = malloc(m); 

    printf("%s ", s); 
    // Copy the contents into ragged_array. 
    assert(t); 
    memcpy(t, s, m); 
    ragged_array[i] = t; 
    ++i; 
    } 

    if (i < ROWS) 
    ragged_array[i] = NULL; 
    /* We DO, however, need to set the termiating entry of this array to 
    * NULL, because, contrary to common misconception, a pointer with all 
    * bits zeroed out is not necessarily a NULL pointer, and there are 
    * implementations in the real world where NULL is a different 
    * special value that traps on some hardware. 
    * 
    * Confusingly, the standard does say that assigning the constant 0 to 
    * a pointer sets it to NULL. 
    */ 

    puts("\n"); 

    for (i = 0; i < ROWS && ragged_array[i]; ++i) { 
    // Print the contents of each row of ragged_array, then free each row. 
    printf("%s ", ragged_array[i]); 
    free(ragged_array[i]); 
    ragged_array[i] = NULL; 
    } 

    puts("\n"); 

    return EXIT_SUCCESS; 
} 
+0

Je n'aurais pas manqué malloc en utilisant le tableau ragged. C'est beau comme tu l'as expliqué. Merci beaucoup :) –

+0

@AshishRanjan De rien. J'ai essayé de le rendre encore plus joli. – Davislor