将char *转换为string,然后分配给struct member:初始化从指针

时间:2017-03-05 06:10:45

标签: c string pointers

我将接收新用户的数据并使用strtok()解析它,它返回一个char *。但是,我无法将char *分配给我的struct成员,它们的类型为char []。我在第52行收到警告:初始化从没有强制转换的指针生成整数。我不明白为什么编译器认为我是从指针做一个整数。我以为我正在为字符串类型(username)分配一个字符串(char username[MAX_USERNAME_LEN + 1])。

有人可以详细说明我的错误(并且可能就如何达到我想要的结果提出建议)?提前谢谢。

#include <stdio.h>  /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), bind(), and connect() */
#include <arpa/inet.h>  /* for sockaddr_in and inet_ntoa() */
#include <stdlib.h> /* for atoi() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */

#define MAXPENDING 5    /* Maximum outstanding connection requests */
#define MAX_MSGS 25 /* Maximum number of messages a user can have in his/her
               inbox = maximum number of messages a user can have in
               his/her Sent folder */
#define MAX_MSG_LEN 500 /* Maximum message length in characters */
#define MAX_USERS 50    /* Maximum number of users that can exist */
#define SERVER_PORT 8000/* The server port number */
#define MAX_RCV_LEN 2048    /* Buffer size in bytes for messages received by socket */
#define MAX_USERNAME_LEN 32
#define MAX_PASSWORD_LEN 32


struct user{
    char username[MAX_USERNAME_LEN + 1];
    char password[MAX_PASSWORD_LEN + 1];
};

/* Array of users */
struct user users[MAX_USERS];
int numberOfUsers;

int main(void) {
    /* THIS WORKS */
    struct user alice = { .username = "alice", .password = "1234"};
    users[0] = alice;
    numberOfUsers ++;

    /* 
     * I will be receiving data for new users and parsing it using
     * strtok(), which returns a char*, so this is why I hoped to be
     * able to add new users in the following manner: */
    char recvBuffer[MAX_RCV_LEN + 1] = "03::billy::1234::";
    char* opCodePtr = strtok(recvBuffer, "::");
    char* usernamePtr = strtok(NULL, "::");
    char* passwordPtr = strtok(NULL, "::");

    char username[MAX_USERNAME_LEN + 1];
    strncpy(username, usernamePtr, MAX_USERNAME_LEN);

    char password[MAX_PASSWORD_LEN + 1];
    strncpy(password, passwordPtr, MAX_PASSWORD_LEN);

    /* The following line gives me the Warning: initialization makes
       integer from pointer without a cast */
    struct user newUser = {.username = username, .password = password};
    users[numberOfUsers] = newUser;
    numberOfUsers ++;

    for (int i = 0; i < numberOfUsers; i ++)
        printf("USER = %s, PASS = %s\n", users[i].username, users[i].password);

    return 0;
}

输出:

USER = alice, PASS = 1234
USER = �, PASS = p 

3 个答案:

答案 0 :(得分:0)

username是指向某些字符的指针,.username是一个字符数组。您无法通过array = pointer填充数组。您需要执行strncpy(array, pointer, size)

之类的操作

请注意,我不知道使用char*返回的strtok是多么安全,因为strtok会修改字符串作为标记,所以我怀疑从储存所有代币中得到的结果实际上可能不会达到预期效果。

答案 1 :(得分:0)

在上面的代码中,您将numberOfUsers增加了两倍,即行号33,54。并且您正在基于for循环中的username打印passwordnumberOfUsers,因此会生成一个附加打印,其中包含垃圾值。因此,根据适当的上下文删除其中一个。

答案 2 :(得分:0)

约翰是对的。请记住,数组名称是其中第一个元素的地址,因此,将其用作右值会产生第一个元素的地址(而不是值),即一个整数,用于初始化数组结构。