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)); 




} 

Dies ist Teil eines ADT und ich habe Probleme zu verstehen, was ich tun muss. Ich weiß, dass ich über den Zeiger auf das Array zugreifen muss, aber ich bin mir nicht sicher, was ich als nächstes tun muss.Erstellen einer neuen Zeichenfolge ADT

Antwort

0

Wenn Sie ein char* in den neuen String Datentyp zu konvertieren sind versuchen, dann können Sie einfach über die Kopieren von Daten direkt mit vorhandenen C-Aufrufen finden Sie 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; 
} 

Oder:

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'; 
    } 
} 
Verwandte Themen