Reputation: 121
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?
Upvotes: 2
Views: 2217
Reputation: 66194
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.
Upvotes: 2