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
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;
}
Related
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define MALLOC(p,s) {\
if (!((p) = malloc(s))) { \
fprintf(stderr, "insufficient memory");\
exit(EXIT_FAILURE);\
}\
}
#define IS_EMPTY(first) (!first)
typedef struct listNode* listPointer;
typedef struct listNode {
int data;
listPointer link;
}listNode;
void printList(listPointer first);
int main(void)
{
int x;
int tmpData;
listPointer first = NULL;
listPointer tmpLink = NULL;
FILE* fp = NULL;
if (!(fp = fopen("in.txt", "r"))) {
fprintf(stderr, "cannot open the file");
exit(EXIT_FAILURE);
}
while (!feof(fp)) {
fscanf(fp, "%d", &tmpData);
MALLOC(tmpLink, sizeof(listNode));
if (IS_EMPTY(first)) {
MALLOC(first, sizeof(listNode));
*tmpLink = *first;
}
tmpLink->data = tmpData;
tmpLink = tmpLink->link;
}
printList(first);
}
void printList(listPointer first)
{
for (; first; first = first->link) {
printf("%d ", first->data);
}
printf("\n");
}
We know that we can implement the insert function.
But I'm really curious about why this doesn't work.
What "first" refers to and what "tmpLink" refers to is the same
After implementing the link list while updating tmpLink,
I'm going to use "first" to print later.
I've spent almost a day just thinking about this, and I've tried debugging it, but I don't know why.
I am making capitalized function. But when execute this code, the bus error occur. Is there anyone can debug this? I really need your help!! please help me . I am computer programming novice without c knowledge.
#include <stdio.h>
void up(char *c)
{
if((*c < ‘z’) && (*c > ‘a’))
{
*c -= 32;
}
}
char *ft_strcapitalize(char *str)
{
int i;
i=0;
while (str[i])
{
up(&str[i]);
i++;
}
return str;
}
int main()
{
char *str = “salut, comment tu vas ? 42mots quarante-deux cinquante”;
ft_strcapitalize(str);
printf(“%s”, str);
}
This solution should work for you.
#include <stdio.h>
void up(char *c)
{
if (!c)
return;
if((*c <= 'z') && (*c >= 'a'))
*c -= 32;
}
char *ft_strcapitalize(char *str)
{
int i;
for (i = 0; str[i]; i++)
up(&str[i]);
return str;
}
int main()
{
char str[] = "salut, comment tu vas ? 42mots quarante-deux cinquante";
ft_strcapitalize(str);
printf("%s\n", str);
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue> // std::priority_queue
using std::vector;
using std::cin;
using std::cout;
struct fj{
int indexI=0;
int freeT=0;
};
struct DereferenceCompareNode : public std::binary_function<fj, fj, bool>
{
bool operator()(const fj lhs, const fj rhs) const
{
return lhs.freeT > rhs.freeT;
}
};
class JobQueue {
private:
int num_workers_;
vector<int> jobs_;
vector<int> assigned_workers_;
vector<long long> start_times_;
void WriteResponse() const {
for (int i = 0; i < jobs_.size(); ++i) {
cout << assigned_workers_[i] << " " << start_times_[i] << "\n";
}
}
void ReadData() {
int m;
cin >> num_workers_ >> m;
jobs_.resize(m);
std::cout<<"Read fault"<<"\n";
for(int i = 0; i < m; i++)
cin >> jobs_[i];
std::cout<<"Read fault ends"<<"\n";
}
void AssignJobs() {
// TODO: replace this code with a faster algorithm.
std::cout<<"Fault point 1"<<"\n";
assigned_workers_.resize(jobs_.size());
start_times_.resize(jobs_.size());
vector<long long> next_free_time(num_workers_, 0);
std::priority_queue<int, vector<int>, std::greater<int> > thread;
std::priority_queue<fj, vector<fj>, DereferenceCompareNode > freeJob;
/*
for (int i = 0; i < jobs_.size(); ++i) {
int duration = jobs_[i];
int next_worker = 0;
for (int j = 0; j < num_workers_; ++j) {
if (next_free_time[j] < next_free_time[next_worker])
next_worker = j;
}
assigned_workers_[i] = next_worker;
start_times_[i] = next_free_time[next_worker];
next_free_time[next_worker] += duration;
}
*/
std::cout<<"dump point 2"<<"\n";
for(int i=0;i<num_workers_;i++){
thread.push(i);
}
std::cout<<"dump point 1"<<"\n";
int counter = 0;
while(jobs_.size()!=0){
std::cout<<"jobs_.size:"<<jobs_.size()<<"\n";
std::cout<<"freeJob.size:"<<freeJob.size()<<"\n";
//check logic
do{
if(freeJob.top().freeT == counter){
std::cout<<"freeJob.top().freeT:"<<freeJob.top().freeT<<"\n";
std::cout<<"counter:"<<counter<<"\n";
thread.push(freeJob.top().indexI);
freeJob.pop();
}else{
break;
}
}
while(freeJob.size()!=0);
std::cout<<"Thread:"<<thread.size()<<"\n";
while(thread.size()!=0){
if(jobs_.size()!=0){
fj currA;
currA.indexI = thread.top();
currA.freeT = jobs_.at(0)+counter;
std::cout<<"currA.indexI:"<<currA.indexI<<"\n";
std::cout<<"currA.freeT:"<<currA.freeT<<"\n";
thread.pop();
jobs_.erase(jobs_.begin());
assigned_workers_.push_back(currA.indexI);
start_times_.push_back(currA.freeT);
}else{
break;
}
}
counter++;
}
}
public:
void Solve() {
ReadData();
AssignJobs();
WriteResponse();
}
};
int main() {
std::ios_base::sync_with_stdio(false);
JobQueue job_queue;
job_queue.Solve();
return 0;
}
I am getting segmentation fault in function ReadData while taking inputs for vector jobs.
I am getting fault even when I am inside bounds of defined size.
Everything was fine when have not written AssignJob function.
Am I doing something wrong with some bounds or taking illegal inputs format or messing with some other stuff?
Am I doing something wrong
Yes, you are: freeJob starts out empty, so this is undefined behavior:
if(freeJob.top().freeT == counter){
In fact, you never push anything into freeJob, you only pop() things from it.
After creating a hash table and assigning each letter to a value for the table, i am noticing the first word output by the table for the beginning of every linked list is the same word. Somehow it seems I am transferring the entire dictionary to each array in the table even though I have attempted to separate them. Any assistance would be awesome! Thanks in advance
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char *word;
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 25;
// Hash table
node *table[N];
char lowerword[LENGTH+1];
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int bucketfind = 0;
int x = 0;
for (int b = word[x]; b != '\0';b = word[x], x++)
{
int lowertemp = tolower(word[x]);
if (x == 0)
{
bucketfind = lowertemp - 97;
}
char lowerfinal = lowertemp;
lowerword[x] = lowerfinal;
//printf("%c", lowerword[x]);
}
int wordlen = x + 1;
int pr = 0;
while (table[bucketfind] -> next != NULL)
{
int dwlen = strlen(table[bucketfind]-> word);
pr++;
//printf("%i, %i, %s, %i\n", pr, dwlen, table[bucketfind] -> word, bucketfind);
}
//TODO
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
int asciifirst = word[0];
int lowerfirst = tolower(asciifirst);
int bucketnum = lowerfirst - 97;
return bucketnum;
}
// Loads dictionary into memory, returning true if successful else false
int dictwords = 0;
//char *cword = (char*)malloc(sizeof(char)*46);
bool load(const char *dictionary)
{
char *cword = malloc(sizeof(char)*46);
FILE *dict = fopen(dictionary, "r");
if (dictionary == NULL)
{
return false;
}
int x = 0;
while ((fscanf(dict, "%s", cword) != EOF))
{
node *nword = malloc(sizeof(node));
nword -> word = cword;
nword -> next = NULL;
int bucket = hash(cword);
//printf("%i\n", bucket);
if (table[bucket] != NULL)
{
nword -> next = table[bucket];
table[bucket] = nword;
}
else
{
table[bucket]= nword;
}
dictwords++;
}
fclose(dict);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return dictwords;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// TODO
return false;
}
It's not just the first word; every word in the linked list is the same word (the last one read). cword gets 46 bytes of memory at a specific address here char *cword = malloc(sizeof(char)*46);. Every word from dictionary is read into that same address.
I am currently unsuccessful at being prompt to add a char for my current program. I am able to add a digit but it will post the prompt to add a character but skips to input portion and directly asks me if I want to continue.
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
main()
{
struct node
{
int num;
char gender[3];
struct node *ptr;
};
typedef struct node NODE;
NODE *head, *first, *temp = 0;
int count = 0;
int choice = 1;
first = 0;
while (choice)
{
head = (NODE *)malloc(sizeof(NODE));
printf("Enter the Student Identification Number\n");
scanf("%d", &head-> num);
printf("Enter the Student gender (M)or(F)\n");
scanf("%c", &head-> gender);
if (first != 0)
{
temp->ptr = head;
temp = head;
}else
{
first = temp = head;
}
fflush(stdin);
printf("Would you like to do another entry(Type No(0) or Yes(1))?\n");
scanf("%d", &choice);
}
temp->ptr = 0;
/* reset temp to the beginning */
temp = first;
printf("\nStudent Information\n");
while (temp != 0)
{
printf("Student ID number: %d\n", temp->num);
printf("Student gender: %c\n", temp->gender);
count++;
temp = temp -> ptr;
}
printf("No. of Students inputted into system: %d\n", count);
}