C:不兼容的类型赋值 [英] C: incompatible types in assignment

查看:156
本文介绍了C:不兼容的类型赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个程序来检查,看是否有端口处于C.特别拷贝参数char数组一一线路畅通。然而,当我尝试编译,它说:

I'm writing a program to check to see if a port is open in C. One line in particular copies one of the arguments to a char array. However, when I try to compile, it says:

错误:不兼容的类型
  分配

error: incompatible types in assignment

继承人的code。该错误是地址

Heres the code. The error is on the assignment of addr

#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv) {
  u_short port;                /* user specified port number */
  char addr[1023];             /* will be a copy of the address entered by u */
  struct sockaddr_in address;  /* the libc network address data structure */
  short int sock = -1;         /* file descriptor for the network socket */

  port = atoi(argv[1]);
  addr = strncpy(addr, argv[2], 1023);
  bzero((char *)&address, sizeof(address));  /* init addr struct */
  address.sin_addr.s_addr = inet_addr(addr); /* assign the address */
  address.sin_port = htons(port);            /* translate int2port num */

  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (connect(sock,(struct sockaddr *)&address,sizeof(address)) == 0) {
    printf("%i is open\n", port);
  }
  if (errno == 113) {
    fprintf(stderr, "Port not open!\n");
  }
  close(sock);
  return 0;
}

我是新的C,所以我不知道为什么会这么做。

I'm new to C, so I'm not sure why it would do this.

推荐答案

地址是一个数组,所以你不能直接分配给它。

addr is an array so you can't assign to it directly.

修改地址=函数strncpy(地址,ARGV [2],1023); 函数strncpy(地址,ARGV [2],1023);

一个指针,你传给什么返回,但并不需要此值。到函数strncpy 通话单独将复制从字符串的argv [2] 地址

A pointer to what you passed in is returned, but this value isn't needed. The call to strncpy alone will copy the string from argv[2] to addr.

请注意:我注意到,有时你在数组的地址传递,有时你数组本身在传递,无需操作员的地址。

Note: I notice sometimes you pass in the address of your array and sometimes you pass in the array itself without the address of operator.

在参数只要求的char * ...

When the parameter only asks for char*...

虽然两者将工作在地址传递,而不是&放大器;地址是比较正确的。 &放大器;地址给出了一个指向一个字符数组字符(*)[1023] ,而地址为您提供了一个的char * 这是第一个元素的地址。它通常并不重要,但如果你做指针算法,然后它会带来很大的区别。

Although both will work passing in addr instead of &addr is more correct. &addr gives a pointer to a char array char (*)[1023] whereas addr gives you a char* which is the address of the first element. It usually doesn't matter but if you do pointer arithmetic then it will make a big difference.

这篇关于C:不兼容的类型赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆