[英]Initialize character pointer array in C
我試圖弄清楚如何初始化char *
數組。 我用char *[100]
屬性定義了一個結構。 當我將字符串數組分配給該屬性時,出現以下錯誤:
#include <stdio.h>
#include <stdlib.h>
#define MAXHIST 100
struct rec
{
int i;
float PI;
char A;
char *arguments[MAXHIST];
};
int main()
{
const char name[5] = "-aefa";
struct rec ptr_one;
// struct rec ptr_one;
(ptr_one).i = 10;
(ptr_one).PI = 3.14;
(ptr_one).A = 'a';
(ptr_one).arguments = { "/bin/pwd", 0};
printf("First value: %d\n",(ptr_one).i);
printf("Second value: %f\n", (ptr_one).PI);
printf("Third value: %c\n", (ptr_one).A);
// free(ptr_one);
return 0;
}
在編譯過程中產生的錯誤是:
hmwk1-skk2142(test) > cc test.c
test.c: In function ‘main’:
test.c:23:27: error: expected expression before ‘{’ token
(ptr_one).arguments = { "/bin/pwd", 0};
在C中,使用索引將值分配給數組:
ptr_one.arguments[0] = "/bin/pwd";
也:
const char name[5] = "-aefa";
是錯的。 字符串末尾的0字節數組必須大一個。 使其長6項,甚至更好:
const char * name = "-aefa";
在這一行:
(ptr_one).arguments = { "/bin/pwd", 0};
您將數組分配與數組初始化混淆了。 實際上,在報告的行中,您試圖為一個指針分配多個值。
您可以嘗試在數組的初始化階段完成操作(同時尊重數組的初始化語義和數組的語法)。
例如
int a[3] = {1, 2, 3};
否則,如果要使用指針符號為數組的元素之一分配值,則可以使用類似於以下代碼的內容:
// assign to a[1] the value 42
*(a + 1) = 42;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.