【问题标题】:Returning type casted array to main function将类型转换的数组返回到主函数
【发布时间】:2013-07-05 11:17:33
【问题描述】:

我正在从返回类型为 char* 的主文件中调用 foo() 函数。从 foo() 我通过类型转换“(char*)ar”返回 int 数组。 ar 是大小为 2 的数组。 现在我可以在 main() 中检索 ar[0] 而不是 ar[1](给出特殊字符)。

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

下面的文件 ch[0] 给出正确的值,而 ch[1] 给出特殊字符

#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;
    }

}

ar[1] 有什么问题,为什么它没有被正确接收?

【问题讨论】:

  • 你会因为未定义的行为和东西而被骂。由于需要对齐不同类型的架构限制,您不能安全地将 int 放入 char* 中。
  • @xaxxon:所以我无法将 int arra 发送到 main.cpp?

标签: c arrays argument-passing


【解决方案1】:

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

printf("Counts :%d \n",((int*)ch)[1];  

【讨论】:

  • 这也给出了与以前相同的结果。
  • 谢谢伙计,效果很好。我在之前的评论中犯了错误!
【解决方案2】:

ch[1] 是 char 数组的第二个元素,因为 char 的维度(可能)与 int 的维度不同,所以您不会得到第二个 int。

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

int* i = (int*)ch;
i[0]; //instead of ch[0]
i[1]; //instead of ch[1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多