0

I am trying different ways of working with struct values but all of them give me error. So, I have the following global struct:

struct Car_ {
    char *currentCar;
    char **cars;
}carPars;

then I am truing to assign *currentCar member to point to the first array of **cars. I am doing it in the following way:

tokenizer->currentToken = tokenizer.tokens[0];

This tells Member reference type 'struct TokenizerT_' is not a pointer; maybe you meant to use '.'?

Then I try in this way

carPars.currentCar = carPars.cars[0];

but when I run my program this actually gives me EXC_BAD_ACCESS (this usually means segmentation fault).

Then I try :

(*curPars).currentCar = (*car).currentCar[0];

but then I have - Indirection requires pointer operand

How would I do it in correct way?

1
  • Since **cars is a pointer to a list of pointers, you will need to have a pointer to the memory area that contains char pointers. Commented Sep 12, 2014 at 12:52

3 Answers 3

1

First, you have to assign memory to cars, the number of arrays you want. Lets say 10:

cars = (char**)malloc (10*sizeof(char));

Then you have to assign memory to each 10 array. Lets say that in each array you want 10 elements:

> for (index = 0; index< 10; index++)
>      cars[index] = (char*) malloc(10*sizeof(char));

Then, to assign to CurrentCar, you can do:

carPars.currentCar = carPars.cars[i];
Sign up to request clarification or add additional context in comments.

Comments

1

You need to assign something to cars first. Presumably you want it to be an array, say of 50 elements:

carPars.cars = calloc(50, sizeof (char*));

1 Comment

ok, got it. Need to allocate memory first. But the what syntax would I use to make proper assignment???
1

you haven't initialized your second member of the carPars variable of type struct Car_. Since there is not any value stored in the double pointer **cars. You may try the following:

 carPars.cars = NULL;
    carPars.currentCar = carPars.cars[0];

if still it doesn't work you may try this:

carPars.cars = (char *)malloc(10*sizeof(char*));
for(i=0; i<5; i++)
    carPars.currentCar = (char)malloc(10*sizeof(char));

here I am assuming that you want to store 10 cars and each car name consists of 10 characters maximum. you can change this value as per your need.

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.