我有这样的数据类型我打电话的ItemType这是一个字符串。
typedef <string> ItemType
Run Code Online (Sandbox Code Playgroud)
我不确定要在“ string>”部分中添加什么。我已经试过如下:
typedef char[] ItemType和
typedef char* ItemType
他们都没有工作。
Itemtype用于我在C语言中创建的arraylist,指示Arraylist元素具有的数据类型。arraylist本身是通用的,因为它接受任何ItemType并在.c文件中实现,而Itemtype在.h头文件中。
编辑1 .c实现代码段:
struct list_type {
ItemType* data;
int size;
int capacity;
};
// adds a component to the array, if enough memory available
void push(ListType listptr, ItemType item) {
if (listptr->size >= listptr->capacity) {
ItemType * temp = malloc(sizeof(ItemType) * (listptr->capacity + 200));
if (temp != NULL) {
listptr->capacity += 200;
memcpy(temp, listptr->data,sizeof(ItemType) * (listptr->size));
free(listptr->data);
listptr->data = temp;
listptr->data[listptr->size] = item;
listptr->size++;
printf("%s inserted:%s ", item, listptr->data[listptr->size]);
}
}
else {
listptr->data[listptr->size] = item;
listptr->size++;
printf("%s inserted:%s ", item, listptr->data[listptr->size]);
}
}
void printl(ListType listptr) {
int i;
for(i = 0; i < listptr->size; i++) printf("%s ", listptr->data[i]);
printf("\n");
}
Run Code Online (Sandbox Code Playgroud)
编辑.h头文件片段
typedef struct list_type *ListType;
typedef char* ItemType;
//other code
void push(ListType l, ItemType item);
Run Code Online (Sandbox Code Playgroud)
这取决于您所说的“字符串”。
如果您的意思char是可以将其数组传递给像这样的函数strcpy(),则很容易
typedef char ItemType[10];
Run Code Online (Sandbox Code Playgroud)
宣称ItemType是的阵列char,其可以保存任何C-样式字符串其strlen()返回9或更小(的差异1是由于终止'\0'终止子串相关的功能(strcmp(),strcat(),strlen())寻找来标记串的结束。
限制是大小是固定的。向写入20个字符ItemType(例如使用strcpy()),并且行为未定义。您有责任确保不会在字符中写入太多字符ItemType。
如果您的意思是某种可以容纳任意长度字符串的类型,而您的代码必须管理其中的内容以确保数据存储足够大,则可以执行以下操作
typedef char *ItemType;
Run Code Online (Sandbox Code Playgroud)
这样做的问题是您的代码需要管理指针指向的内存。 ItemType是指针,而不是可以保存数据的数组。
#include <stdlib.h> /* declares malloc(), realloc(), free(), etc */
/* and in a function somewhere */
ItemType x = malloc(25);
/* can use any operations that do not copy more than 24 characters to x */
/* but if we want a larger string, we have to manage it */
ItemType temp = realloc(50);
if (temp == NULL) /* reallocation failed */
{
/* work out how to recover or terminate */
}
else
{
x = temp;
}
/* If reallocation failed and no recovery is done, do not execute the following code */
/* can now treat x as an array of 50 characters (i.e. if we ensure strlen(x) never exceeds 49 */
free(x); /* when we are done with x */
Run Code Online (Sandbox Code Playgroud)
如果您想要一个可以根据需要自行调整大小的字符串类型(例如,某些其他语言所提供的大小),那么C语言中就没有办法。