Returning type casted array to main function
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]=' ';
if( (bytecount=send(hsock, buffer, strlen(buffer)-1,0))== -1){
fprintf(stderr, "Error sending data %dn", errno);
goto FINISH;
}
if((bytecount = recv(hsock, ar, 2 * sizeof(int), 0))== -1){
fprintf(stderr, "Error receiving data %dn", 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 filenamen", 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?
You're getting a character then converting it to an int so you're only seeing the first 8 bytes. You need to convert to an int* first (but this is not a good thing to do H2CO3 will tell you why most likely)
printf("Counts :%d n",((int*)ch)[1];
ch[1] is the second element of an array of chars, since the dimension of a char is (possibly) different from the dimension of an int you are not getting the second int.
You should return an int* or, at least, convert the char* to an int* in the main
int* i = (int*)ch;
i[0]; //instead of ch[0]
i[1]; //instead of ch[1]
链接地址: http://www.djcxy.com/p/72170.html
上一篇: int main()和void main()如何工作
下一篇: 将类型化数组返回到主函数