user6161 user6161 - 14 days ago 5
C Question

char array showing empty trying to append second string

I just want to store(append/cancatenate) three mobile numbers in a char array. In a for loop I'm giving three mobile numbers. I wrote a function to store the mobile
numbers. The char array stores the first mobile number by printing the length of the array variable. When I try to store the second mobile number the char array becomes null (length of the array is zero). Actually the variable array "auth_mob_no" index is incremented continuously (

j++
) and to get the second number need to set variable array "mob_no" index to zero (k=0). Why is not storing the strings after I gave the first string?

#include <stdio.h>
#include <string.h>

char mob_auth(char mob_no[]);
int i,j=0,k=0;

int main()
{
char num[15];
for(i=0;i<3;i++)
{
scanf("%s",num);
if(mob_auth(num))
{
printf("Mobile Number stored\n");
}
}
return 0;
}

char mob_auth(char mob_no[])
{
char auth_mob_no[50];
while(mob_no[k]!='\0')
{
auth_mob_no[j]=mob_no[k];
k++;j++;
}
auth_mob_no[j]='\0';
k=0;
printf("len:%d\n",strlen(auth_mob_no));
return 1;
}


Output:

input by user: +919999999999
len:13
Authicated Mobile Number

input by user: +918888888888
len:0
Authicated Mobile Number

Answer

auth_mob_no is automatic variable, so its contents will vanish on exiting its scope (returning from mob_auth in this case).

To correct, do either one of these:

  • Add static before char auth_mob_no[50]
  • Remove the local variable auth_mob_no and make it global like you did for j and k

Also note that the line printf("len:%d\n",strlen(auth_mob_no)); will invoke undefined behavior by passing data having wrong type to printf().

Use correct format specifier

printf("len:%zu\n",strlen(auth_mob_no));

or cast the data before passing (because the length will be small enough in this case)

printf("len:%d\n",(int)strlen(auth_mob_no));
Comments