3

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?

4

2 回答 2

1

你得到一个字符,然后将它转换为一个 int,所以你只看到前 8 个字节。您需要先转换为 int*(但这不是一件好事,H2CO3 会告诉您原因很可能)

printf("Counts :%d \n",((int*)ch)[1];  
于 2013-07-08T07:45:21.230 回答
1

ch[1] 是字符数组的第二个元素,因为 char 的维度(可能)与 int 的维度不同,因此您没有得到第二个 int。

您应该返回一个 int* 或至少将 char* 转换为 int* 在 main

int* i = (int*)ch;
i[0]; //instead of ch[0]
i[1]; //instead of ch[1]
于 2013-07-08T07:45:58.577 回答