0

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};
3
  • 2
    Arrays cannot be assigned. Assign it's elements one be one. Do not mix up assignment and initialisation. Commented Sep 24, 2016 at 16:13
  • You are using array as lvalue. Commented Sep 24, 2016 at 16:14
  • ptr_one is not a pointer. Don't use missleading names. Commented Sep 24, 2016 at 16:17

2 Answers 2

1

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";
Sign up to request clarification or add additional context in comments.

3 Comments

const char * name = "-abcd" is not wrong. const char name[5] = "-abcd" is wrong.
Why is it wrong? Because you expected that the last element of the array is the terminating character?
Every C standard function expects the last element of a string to be '\0'. The literal "-abcd" is the same as ['-', 'a', 'b', 'c', 'd', '\0']. Thus the array is 6 long not 5. Use const char name[6] or even better const char *.
0

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.

e.g.

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.