[英]Dynamic string array struct in C
我必須在c中編寫一個函數,它將返回一個動態的字符串數組。 這是我的要求:
您可以使用malloc()分配任意長度的數組(在Java中類似於“new”),並使用realloc()使其增長或縮小。
你必須記住用free()釋放內存,因為在C中沒有garbarage收集器。
檢查: http : //www.gnu.org/software/libc/manual/html_node/Memory-Allocation.html#Memory-Allocation
編輯:
#include <stdlib.h>
#include <string.h>
int main(){
char * string;
// Lets say we have a initial string of 8 chars
string = malloc(sizeof(char) * 9); // Nine because we need 8 chars plus one \0 to terminate the string
strcpy(string, "12345678");
// Now we need to expand the string to 10 chars (plus one for \0)
string = realloc(string, sizeof(char) * 11);
// you can check if string is different of NULL...
// Now we append some chars
strcat(string, "90");
// ...
// at some point you need to free the memory if you don't want a memory leak
free(string);
// ...
return 0;
}
編輯2:這是分配和擴展字符指針數組的示例(字符串數組)
#include <stdlib.h>
int main(){
// Array of strings
char ** messages;
char * pointer_to_string_0 = "Hello";
char * pointer_to_string_1 = "World";
unsigned size = 0;
// Initial size one
messages = malloc(sizeof(char *)); // Note I allocate space for 1 pointer to char
size = 1;
// ...
messages[0] = pointer_to_string_0;
// We expand to contain 2 strings (2 pointers really)
size++;
messages = realloc(messages, sizeof(char *) * size);
messages[1] = pointer_to_string_1;
// ...
free(messages);
// ...
return 0;
}
考慮創建適合您問題的適當類型。 例如,您可以創建一個包含指針和sn整數長度的結構來表示動態數組。
你對examine()
函數的原型設置和你必須編寫的函數有一些限制嗎? (我們稱之為validate()
)
你說你有10個examine()
函數,它是否意味着你將在validate()
返回的數組中最多有10條消息/結果?
我是一名具有C背景的Java程序員,所以也許我可以為你強調一些事情:
在C中沒有等效的Array.length:你必須提供一個邊整數值來存儲數組的有效大小
C數組不能“增長”:你必須使用指針並分配/重新分配數組開始指針指向的內存,因為這個數組增長或縮小
你應該已經知道C中沒有類或方法的概念,但是你可以使用struct
, typedef
和函數指針來為你的C程序添加某種面向對象/通用性行為......
根據您的需求和義務,數組可能是一個好的方式:或許您應該嘗試找出一種在C中構建/查找等效的java List接口的方法,以便您可以添加,刪除/銷毀或排序檢查結果元素,而不必在每次操作結果集時重復內存分配/重新分配/釋放代碼(並且您應該發送帶有結構/檢查函數的頭文件來描述您現在所做的事情,並表達你需要更准確一點,這樣我們就可以引導你走向好的方向)
不要猶豫,提供更多信息或詢問有關上述子彈點的具體信息;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.