简体   繁体   English

在C中初始化字符指针数组

[英]Initialize character pointer array in C

I'm trying to figure out how to initialize an array of char * . 我试图弄清楚如何初始化char *数组。 I defined a struct with a char *[100] attribute. 我用char *[100]属性定义了一个结构。 When I assigned a string array to that attribute, I got the error that is shown below: 当我将字符串数组分配给该属性时,出现以下错误:

#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;
}

The error that is produces during the compilation is: 在编译过程中产生的错误是:

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};

In C assign values to the array using the indices: 在C中,使用索引将值分配给数组:

ptr_one.arguments[0] =  "/bin/pwd";

Also: 也:

const char name[5] = "-aefa";

is wrong. 是错的。 The array needs to be one item bigger for the 0-byte at the end of the string. 字符串末尾的0字节数组必须大一个。 Make it 6 items long, or even better: 使其长6项,甚至更好:

const char * name = "-aefa";

In this line: 在这一行:

(ptr_one).arguments = { "/bin/pwd", 0};

You are confusing arrays assignment with arrays initialization. 您将数组分配与数组初始化混淆了。 In fact, in the reported line you are trying to assign more than one value to one pointer. 实际上,在报告的行中,您试图为一个指针分配多个值。

What you are trying to do can be done (by respecting both the arrays initialization semantic and the arrays syntax) at the initialization phase of the array. 您可以尝试在数组的初始化阶段完成操作(同时尊重数组的初始化语义和数组的语法)。

eg 例如

int a[3] = {1, 2, 3};

Otherwise, if you want to assign a value to one of the element of the array by using the pointers notation you can use something similar to the following code: 否则,如果要使用指针符号为数组的元素之一分配值,则可以使用类似于以下代码的内容:

// assign to a[1] the value 42
*(a + 1) = 42;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM