[英]c pass struct to method for updating
以下代碼段存在一些問題:
#include <stdio.h>
struct some_numbers
{
int id;
char *somestring;
};
typedef struct some_numbers numb;
void print_numbers(numb *a)
{
printf("%d: %s\n", a->id, a->somestring);
}
void add_number(numb *a)
{
// do someting magical
// push the new result to the existing struct
// put something into like:
a->somestring[5] = "widdley";
}
int main(void)
{
// put some stuff in the struct
numb entries[50];
int x;
for(x=0; x < 4; x++)
{
numb a = entries[x];
a.id = x;
a.somestring = "goats";
print_numbers(&a);
}
add_numbers(&a); // i want to call a method
return 0;
}
我想創建一個結構數組,將該結構傳遞給方法,然后將更多項目彈出該數組。 到目前為止,我嘗試過的所有方法都失敗了,我很難思考如何擺脫這個難題。 我可以打印這些值而沒有任何問題:
> ./struct
0: goats
1: goats
2: goats
3: goats
>
我希望輸出看起來像:
> ./struct
0: goats
1: goats
2: goats
3: goats
4: widdley
>
請幫忙。 我不擅長c,所以要溫柔!
編輯:澄清了代碼示例以將焦點從錯誤的區域移開。
這里:
a->somestring[5] = "widdley";
somestring[5]
的類型是char
,而不是char*
。 如果需要字符串數組,則需要定義:
struct some_numbers {
int id;
char *somestring[20]; // 20 is an example
};
並根據您的實際目標以某種方式管理這些字符串。
如果要將新數字添加到entries
,請使用四個以上的entries
進行定義,並跟蹤有效位置:
numb entries[20]; // 20 is an example
int num_entries = 0;
entries[num_entries++] = new_entry(); // some function that returns an entry
或僅使用需要動態內存管理(malloc / realloc)的動態數組;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct some_numbers
{
int id;
char *somestring;
};
typedef struct some_numbers numb;
void print_numbers(numb *a) {
printf("%d: %s\n", a->id, a->somestring);
}
void add_entry(numb **list, int *n, int id, const char *str) {
int cnt = *n;
*list = realloc(*list, sizeof(numb)*(cnt + 1));
(*list)[cnt].id = id;
(*list)[cnt].somestring = malloc(strlen(str)+1);
strcpy((*list)[cnt].somestring, str);
*n = cnt + 1;
}
int main(void)
{
// put some stuff in the struct
numb *entries = 0;
int x, num_entries=0;
for(x=0; x < 4; x++)
{
add_entry(&entries, &num_entries, x, "goats");
}
for (x=0; x<num_entries; x++)
print_numbers(&entries[x]);
printf("\n\n");
add_entry(&entries, &num_entries, 6, "widdley");
for (x=0; x<num_entries; x++)
print_numbers(&entries[x]);
return 0;
}
如果要向數組添加更多值,則需要預先分配足夠的內存以存儲最大數量的結構,或者動態分配內存。 所以:
numb entries[100];
要么
numb *entries = malloc(sizeof(numb)*100);
然后,您需要將變量傳遞給add_number函數以跟蹤數組的結束位置:
void add_number(numb *a, int position) {
a[position].somestring = "widdley";
}
您已注釋掉對add_numbers()
的調用,因此,數組中的結構當然不會改變。 我懷疑您這樣做是因為您遇到了編譯器錯誤。 a->somestring[5] = "widdley";
應該是a->somestring = "widdley";
因為您要設置整個字符串的值,而不僅僅是該字符串中的一個字符。 將來,請發布您遇到的所有編譯器錯誤。 在對代碼進行這一更改之后,應在調用add_numbers()
之后打印出數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.