我從返回類型爲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],爲什麼沒有正確接收?
你會得到大聲呵斥爲未定義行爲和東西。由於不同類型需要對齊的體系結構限制,因此不能安全地在char *中引入整數。 – xaxxon
@xaxxon:所以我不能發送int陣列到main.cpp? – user123