user1324258
user1324258

Reputation: 561

casting a struct in c

I need an array of user structs.

struct user {
    char *username;
};  

struct user users[10]; //Array of user structs

int main(int argc, char **args) {
    int initUsersArray();        
    char *username = "Max";
    addToUsersArrry(username);

}



int addToUsersArrry(username) {
int i;
i = 0;
struct user tmp;    
for(i;i<10;i++) {
    if(users[i] != NULL) 
        if(strcmp(*users[i].username,username)==0)
            return -1;
}
i = 0;
for(i;i<10;i++) {
    if(users[i] = NULL) { 
        users[i]=tmp;
        users[i].username=username;
        return 1;
    }   

}   

}

int initUsersArray() {  
int i;
i=0;
struct user tmp;

for(i;i<10;i++) {
    users[i] = (struct user*) calloc(1,sizeof(tmp));
}
}

My first question is, if it is the right way to init the users array with NULL like i did. The second problem is, that *users[i].username and other parts of code where want to get/set the user at a specific position, dont work. Regards

Upvotes: 2

Views: 151

Answers (1)

nullpotent
nullpotent

Reputation: 9260

Here, I fixed it for you. And don't forget to diff and learn something. Don't just c/p it.

#include <stdio.h>
#include <stdlib.h>

typedef struct user {
    char *username;
} user;

user *users; //Array of user structs

int addToUsersArray(char *username) {
int i = 0;

for(; i<10; i++) {
    if(users[i].username=='\0') {
        users[i].username = username;
    return 1;
    } else if(strcmp(users[i].username, username) == 0)
    return -1;
}
return -1;
}

void initUsersArray() {  
    users = (user*) calloc(10, sizeof(user)); //10 of them
}

int main(int argc, char** argv) {
    initUsersArray();        
        char *username = "Max";
        addToUsersArray(username);
    username = "Ma1x";
    addToUsersArray(username);
    printf("%s\n",users[0].username);
    printf("%s\n",users[1].username); 
    return 1;
}

Upvotes: 1

Related Questions