I will be receiving data for new users and parsing it using strtok(), which returns a char*. However, I am having trouble assigning the char* to my struct members, which are of the type char[]. I am getting the warning on line 52: Initialization makes integer from pointer without a cast. I don't understand why the compiler thinks I am making an integer from a pointer. I thought I was assigning a string (username) to a string type (char username[MAX_USERNAME_LEN + 1]).
Can someone please elaborate on my error (and perhaps give a suggestion on how to achieve my desired result)? Thanks in advance.
#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; } Output:
USER = alice, PASS = 1234 USER = �, PASS = p
strncpy(users[numberOfUsers].username, usernamePtr, MAX_USERNAME_LEN); strncpy(users[numberOfUsers].password, passwordPtr, MAX_PASSWORD_LEN);does the trick.