0

I'm practicing string in C language and I'm posting a question because I got an unwanted result.

I saved the string in the order of 123, 456, 789, but //Here output is 789,789, 789.

I would appreciate it if you could point out the wrong part.

Thank you for reading it.

#include <stdio.h>
#include <stdlib.h>

typedef struct Que
{
    char *s;
    int t;
} QUE;
QUE que[50];
int wp;
void push(char *s)
{
    que[wp].s = s;
    printf("que[wp].s = %s\n",que[wp].s);
    wp++;
}

int cnt = 0;

char * input(char *str)
{
    static char arr[3];
    
    if(cnt == 0)
    {
        arr[0] = '1';
        arr[1] = '2';
        arr[2] = '3';
    }
    else if(cnt==1)
    {
        arr[0] = '4';
        arr[1] = '5';
        arr[2] = '6';
    }
    else if(cnt==2)
    {
        arr[0] = '7';
        arr[1] = '8';
        arr[2] = '9';
    }
    
    cnt++;
    
    return arr;
}


void Temp()
{   
    char *a = "123";
    
    for(int i=0; i<3; i++)
    {
        char *Nchk = malloc(sizeof(char)*3);
        
        Nchk = input(a);
        printf("Nchk = %s\n",Nchk);
        push(Nchk);
        free(Nchk);
    }

    // Here...!!
    printf("%s\n",que[0].s);
    printf("%s\n",que[1].s);
    printf("%s\n",que[2].s);
}


int main(void){
    int ans = -1;
    Temp();
    return 0;
}

//Here...! I was also expecting the queue value to be 123, 456, 789.

Duncan
  • 1
  • Welcome to SO. You do not have any string in your code except for `"123"`. Strings in C are nul-terminated character sequences. You miss the termination and also the memory for termination – Gerhardh Dec 20 '22 at 11:27
  • Your call to `malloc` causes a memory leak because you throw away the address in the next line. Maybe you wanted to copy result from `input` into that memory? – Gerhardh Dec 20 '22 at 11:28
  • Array `arr` in function `input` only exists once in memory. All your queue elements point to that same array. Therefore you only see what was stored last. – Gerhardh Dec 20 '22 at 11:30
  • I've linked two duplicates. The first tells you how to copy strings. The second tells you what strings are. I would however strongly recommend to read the chapter "strings" in your C book, and before it the chapter about pointers. – Lundin Dec 20 '22 at 12:24
  • Gerhardh, Lundin, Thanks for the reply. I understood according to your advice. Thanks. – Duncan Dec 21 '22 at 01:14

0 Answers0