I am running my C program on 64 bit linux. I have written two small functions to which I will pass a char array and it will be filled by the function and returned back.
I am facing some issues with the first function func1().
The function are func1:
void func1(char *str1)
{
short optiony = 0;
printf("\tfunc1: str1 at %u\n", str1);
printf("\tProvide the option:\n");
scanf("%d", &optiony);
if(optiony== 1)
{
strcpy(str1, "168.98.173.44");
}
printf("\tfunc1: str1 at %u is %s\n", str1, str1);
}
func2:
void func2(char *str2)
{
short optiony= 0;
printf("\tfunc2: str2 at %u\n", str2);
printf("Provide the option:\n");
scanf("%d",&optiony);
if(optiony== 1)
{
strcpy(str2, "168.97.176.146");
}
printf("\tfunc2: str2 at %u is = %s\n", str2, str2);
}
main:
main(int argc, char* argv[])
{
char str1[10] = "\0";
char str2[10] = "\0";
printf("main: str1 at %u\n", &str1);
func1(str1);
printf("main: str1 at %u is %s\n\n", &str1, str1);
printf("main: str2 at %u\n", &str2);
func2(str2);
printf("main: str2 at %u is %s\n", &str2, str2);
return(0);
}
The output is:
main: str1 at 4149951616
func1: str1 at 4149951616
Provide the option:
1
func1: str1 at 4149951616 is 168.98.173.44
main: str1 at 4149936112 is
^
|
--------------------------------note the change of address
main: str2 at 4149936096
func2: str2 at 4149936096
Provide the option:
1
func2: str2 at 4149936096 is = 168.97.176.146
main: str2 at 4149936096 is 168.97.176.146
The problem occuring is in the main program after the call returns from func1() the address of the variable passed to it looks changed. Due to this the value set inside the function is not reflecting in main. The issue is not occuring in func2().
What is bug in this code?
%pformat specifier. And don't scanf shorts with%d, useintinstead.char []s.