1

I have 2 files in msg format. msg format is not important here.

car.msg

int speed;
int width;

cararr.msg

car mycar[];

I want to print all the information about all the cars that are present but I have no clue about the number of cars present(how big is the array) so I use the following technique to print the information.

so I do this:

cararr* ptr2car;
for(int i=0;mycar[i] != '\0'; i++){
      cout << ptr2car->mycar[i].speed <<endl;
      cout << ptr2car->mycar[i].width <<endl;
}

Despite this, I am receiving errors. I do not know what did I do wrong. I have no clue what approach should I use to get this output. please Help

Also why should I take a pointer to cararr, when I can just take an instance of cararr inst2car and do something like this:

 cararr inst2car;
    for(int i=0;mycar[i] != '\0'; i++){
          cout << inst2car.mycar[i].speed <<endl;
          cout << inst2car.mycar[i].width <<endl;
    }

thanks

4
  • 2
    does cararr have a mycar member? also you may wanna try only mycar[i] instead of mycar[i] != '\0' Commented Aug 2, 2013 at 10:57
  • This all really really depends on what the msg file is (are you using ROS?), what the structure generated for those files are, how the data obtained etc. For example, you don't show us how ptr2car is instantiated. Maybe it's dynamic memory so it has to be pointer. Commented Aug 2, 2013 at 10:58
  • By the way, you use ptr2car->mycar inside the loop, but only mycar as the loop condition. Is that your compilation error? Not to mention you can't compare a struct with an integer. Commented Aug 2, 2013 at 10:58
  • Yes I am using ROS. I think the problem is that I cannot use mycar[i] != '\0' because its not a char. Also maybe I should also change the loop condition and add ptr2car->mycar[i] in the loop. I will check and inform. Commented Aug 2, 2013 at 11:06

1 Answer 1

1

In general you need to know exactly what's at the end of the array. You need some sort of sentinel value to use as a delimiter to indicate the end of the array.

'\0' used in c strings is an example of such delimiter.

You need to ensure the last element in the array is such delimiter and check for it in the condition.

It's hard to give you more specific answer with such generic question.

For example, if you knew the last element will have speed -1, you can use that:

for(int i=0;mycar[i].speed != -1; i++) {
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah thats the problem. I am detecting different cars and I have no clue about the number or the parameters of the car. Everytime there might be a different reading.

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.