简体   繁体   中英

Initialize character pointer array in C

I'm trying to figure out how to initialize an array of char * . I defined a struct with a char *[100] attribute. 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:

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. Make it 6 items long, or even better:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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