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.