2

How can I remove first two elements of a string array? I have a code which is something like this.

char *x[10];
..............
..............
..............
char *event[20];
event[0]=strtok(x[i]," ");
event[1]=strtok(NULL," ");
event[2]=strtok(NULL," ");
event[3]=strtok(NULL," ");
event[4]=strtok(NULL," ");
event[5]=strtok(NULL," ");
for(i=2;i<length;i++)
{
    strcpy(event[i-2],event[i]);
}

I observed that only event[0] has proper values. I printed the contents of event[][] before for loop and it displays correctly. Could you please tell me why this is wrong? and a possible solution?

1
  • 1
    What is the expected output and what is the output which you are getting? Commented Dec 6, 2012 at 4:40

1 Answer 1

2

You should not be using strcpy() in this code. The API strtok() will return you a pointer to the delimited token discovered within the original source buffer after terminating at the discovered delimiter. Therefore, you're using strcpy() where you should not be.

Your events[] array has pointers returned from strtok(). Just throw out the first two pointers and move the others down:

for(i=2;i<length;i++)
    event[i-2] = event[i];
length -= min(length, 2);

Note: the min() is required to ensure your length, signed or unsigned, never wraps below zero (if signed) or UINT_MAX (if unsigned) in the event length is undersized on entry.

Sign up to request clarification or add additional context in comments.

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.