2017-10-02 5 views
0
typedef struct _String { 
    char storage[40]; 
} string; 

// Create a new `String`, from a C-style null-terminated array of 
// characters. 
String newString (char *str) { 
//INSERT CODE HERE 
    *str = malloc(1 * sizeof(string)); 




} 

Cela fait partie d'un TDA et j'ai de la difficulté à comprendre ce que je dois faire. Je sais que j'ai besoin d'accéder au tableau via le pointeur, mais je ne suis pas sûr de ce que je dois faire ensuite.Création d'une nouvelle chaîne ADT

Répondre

0

Si vous essayez de convertir un simple char* dans le nouveau type de données String alors vous pouvez copier les données directement avec les appels existants C, voir here:

#include <string.h> 

#define STRING_MAX 40 

typedef struct _String 
{ 
    char storage[STRING_MAX]; 
} String; 

String newString (char *str) 
{ 
    String s; 

    // Make sure that 'str' is small enough to fit into String. 
    if(strlen(str) < STRING_MAX) 
    { 
    strcpy(s.storage, str); // Use the built-in C libraries. 
    }  
    else 
    { 
    s.storage[0] = '\0'; // Default to a null string. 
    } 

    return s; 
} 

Ou:

String newString(char* str) 
{ 
    String s; 
    int i = 0; 

    // Copy over every character and be sure not to go out of 
    // bounds STRING_MAX and stop once a null is reached. 
    while(i < STRING_MAX && str[i] != '\0') 
    { 
    s.storage[i] = str[i]; 
    i++; 
    } 

    // If the copy finished then put a null at the end since we skipped 
    // copying it before in the WHILE loop. 
    if(i < STRING_MAX) 
    { 
    s.storage[i] = '\0'; 
    } 
}