0
votes

I want to implement a queue which holds 10 elements of char * array. I searched on the internet but couldn't find enough solutions. I have a char array:

char str[50]: 
char *arr[5];

And the user enters some string with backspace character e.g "Hello I am computer". The string is in str[] array. I token them with strtok() function and assign it to the arr[].Then it becomes:

//arr[0] = "Hello"
//arr[1] = "I"
//arr[2] = "am"
//arr[3] = "computer"

It is ok until now, I am doing it correctly.

Now my question is how to hold this whole arr array in queue's first node or element. There are lots of examples about queue that holding int values and they are easy to understand, but I couldn't do the char * version.

2
can you use structs? how is your queue being implemented? (arrays? lists? etc.) - arjayosma
Just replace int with char *? The queue itself should not differ at all. - Osiris
Should I use char**(malloc) instead of int*(malloc) - Cemil Çakmak

2 Answers

0
votes

As far as I understood your question you need to implement a queue of type string.

You can do it as you do with any other queue.But instead of int it would of type char* you would also need to pass length of the word so you could dereference that many number of char starting from the char pointer till length of the word.

void Enqueue(char* x, int len)
{
    // if empty 
        front = rear = 0; 
    // else 
        rear = (rear+1);
    char ch[100];
    for(int i=0;i<len;i++) {
        ch[i] = *(x+i);
    }
    Arr[rear] = ch;
}
0
votes

First of all you have to be careful when saving an address to a variable that you want to use later. You have to ensure that the address hold by the pointer is still valid when you read from it:

int main()
{
   char str[] = "Hello I am computer";   // "Hello I am computer" is stored on the stack
   AddStringToQueue(str[0]);   
}
// str could be overwritten by another function who allocates local variables

As you said in the comment you should use void* malloc(sizeof("Hello I am computer")) which return the start pointer of your allocated memory.

The other thing is why you want to store the string as tokens? Wouldn't it be easier to store the whole string ("Hello I am computer") and use the first character as your start address for the string? If you need it as tokens you maybe can call strtok() after you read out the queue.

Let me make an example:

#define QUEUE_MAX 10
int QueuePos = 0;
char* Queue[QUEUE_MAX];
memset(Queue, NULL, sizeof(Queue));

// call AddStringToQueue("Hello I am computer"); anywhere

void AddStringToQueue(char* string)
{
   char* ptr = (char*)malloc(sizeof(string));
   memcpy(ptr, string, sizeof(string));
   Queue[QueuePos++] = ptr;
   if (QueuePos == QUEUE_MAX) QueuePos = 0;  // overwrites Queue if max. is reached
}

I am not sure if you mean this.

Hope it helps.

PS: I didn't compiled this so i am not sure if it works, it should just be an example.