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));
}
这是ADT的一部分,我无法理解我需要做什么。我知道我需要通过指针访问数组,但我不确定接下来我需要做什么。
答案 0 :(得分:0)
如果您尝试将char*
转换为新的String
数据类型,则只需使用现有的C调用直接复制数据,请参阅here:< / p>
#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;
}
或者:
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';
}
}