I am calling foo() function from main file whose return type is char*. from foo() I am returning int array by typecasting "(char*)ar". ar is array of size 2. Now I can retreive ar[0] in main() not ar[1](gives special char).
foo.c
#include <string.h>
int ar[2];
char *foo(char* buf)
{
//static ar[2] this also gives same problem
//various task not concen with ar[]
buf[strlen(buf)-1]='\0';
if( (bytecount=send(hsock, buffer, strlen(buffer)-1,0))== -1){
fprintf(stderr, "Error sending data %d\n", errno);
goto FINISH;
}
if((bytecount = recv(hsock, ar, 2 * sizeof(int), 0))== -1){
fprintf(stderr, "Error receiving data %d\n", errno);
goto FINISH;
}
printf("Positive count: %d \nNegative count: %d \n",ar[0],ar[1]); //This prints correct values
close(hsock);
FINISH:
;
printf("array item2 %d \n",ar[1]); // Gives correct value for ar[0] and ar[1]
return (char *)ar;
}
main.cpp
here in below file ch[0] gives correct values while ch[1] gives special character
#include<stdio.h>
#include<string.h>
#include "foo.h"
int main(int argc, char *argv[] )
{
char buffer[1024];
char *ch;
strcpy(buffer,argv[1]);
printf("Client : \n");
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
printf( "\n%s filename\n", argv[0] );
}
else
{
printf("\nstring is :%s \n",buffer);
ch=foo(buffer);
printf("Counts :%d \n",(int)ch[1]); //Here (int)ch[0] and ch[1] special char
return (int)ch;
}
}
What's wrong with ar[1], why it does not get received correctly?