c - 将类型转换数组返回到主函数

标签 c arrays argument-passing

我从返回类型为 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,因此您只能看到前 8 个字节。您需要先转换为 int*(但这不是一件好事,H2CO3 很可能会告诉您原因)

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

关于c - 将类型转换数组返回到主函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17521303/

相关文章:

c - 如何像 php 中的 substr 一样使用定界符(空格)分割字符串?

c - while 循环和 if 与 C 中的 readdir() 相处不好

c - 返回指向字符串的指针数组

java - 在特定 INPUT 值后获取 ArrayIndexOutOfBoundsException

c - 如何将二维数组传递给 C 函数

php - 函数中的可变长度引用参数列表

c - printf 作为函数的参数

c - 获取(不显示)C 中的文件和文件夹列表

c - 什么是扩展名为 .a 的文件?

python - 从两个给定的整数中生成唯一整数 Python Numpy