I am trying to change the number that identifies different structures dynamically (being the last digit of the struct name meant to be the same as the i variable).
Here is an example of what I mean:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char * name;
char * job;
int age;
};
int main () {
time_t t;
srand((unsigned) time(&t));
long random = rand() % 20;
for (int i = 0; i != (random + 1); i++) {
struct Person strcat("Person", i");
}
return 0;
}
I would like that for each i the struct's name changed. So let's say that i = 2. I would like the struct name to be Person2.
Is there any way for me to do this in C?
No, that is not possible. identifiers in C don't change at run-time. In fact, for variables, they generally don't even exist at runtime.
As #VladFromMoscow suggests, what you're probably after is an array of struct Person's, e.g.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char * name;
char * job;
int age;
};
#define MAX_PERSON_NAME_LENGTH 50
#define MAX_NUM_PERSONS 20
int main () {
time_t t;
srand((unsigned) time(&t));
long random = rand() % MAX_NUM_PERSONS;
struct Person persons[random];
for (int i = 0; i != (random + 1); i++) {
persons[i].name = malloc(MAX_PERSON_NAME_LENGTH + 1);
if (persons[i].name != NULL) {
sprintf(persons[i].name, "The %d'th person", i);
}
else {
perror("allocating memory for a person name");
exit(EXIT_FAILURE);
}
}
// do something with persons
return 0;
}
no, but there's no need for such a function anyway. you can achieve what you want by simply creating an array of structs. So, you will access them by doing Person[0], Person[1] etc.. instead of creating 1 different name for each structure
Related
In my code below there are two structs. One called person and one called person_list which holds by reference a list of person structs or 'people'.
I want to fill in (or reference) 10 person structs within person_list but upon running this code I am getting a segmentation fault. How can I handle or declare the memory for each person so this works?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 50
#define MAX_PEOPLE_ALLOWED 10
struct person_list {
struct person *people[MAX_PEOPLE_ALLOWED];
};
struct person
{
char name[MAX_LENGTH];
//int age;
};
int main(int argc, char *argv)
{
struct person_list list;
struct person pers[10];
int i;
char name[MAX_LENGTH];
for (i = 0; i < MAX_PEOPLE_ALLOWED; i++) {
sprintf(descrip, "I am person number: %d", i);
strcpy( &pers[i].name, name);
list.people[i] = &pers[i];
}
}
#BDillan ,I have made some simple corrections to your code, hope that you are looking for something similar to this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 50
#define MAX_PEOPLE_ALLOWED 10
struct person_list {
struct person *people[MAX_PEOPLE_ALLOWED];
};
struct person
{
char name[MAX_LENGTH];
//int age;
};
int main()
{
struct person_list list;
struct person pers[10];
char descrip[MAX_LENGTH];
int i;
char name[MAX_LENGTH];
for (i = 0;i < MAX_PEOPLE_ALLOWED; i++)
{
sprintf(descrip, "I am person number: %d", i);
strcpy(pers[i].name,descrip);
//puts(pers[i].name);
list.people[i] = &pers[i];
}
//to display the details of persions entered above
for (i = 0;i < MAX_PEOPLE_ALLOWED; i++)
printf("%s \n",list.people[i]->name);
}
I have the following code in C:
typedef struct
{
int age;
int phoneNumber;
} Student;
typedef struct
{
int id;
int student[1];
} People;
#define NUM_OF_PEOPLE
void *p = malloc(sizeof(People) + sizeof(int) * NUM_OF_PEOPLE + sizeof(Student) * NUM_OF_PEOPLE);
How could I find the pointer to the memory point to the first element of struct Student in the memory?
I try to do it in the following way:
int i = 0;
for(i = 0; i < NUM_OF_PEOPLE; i++)
{
Student * student_p = p.student[NUM_OF_PEOPLE];
}
It does not work, so can we allocate memory in the way?
And how to find the first element of struct Student in the memory?
What you have is an ancient way of having a flexible array member, which was technically also undefined behavior.
You are looking for this.
First, you need to define your struct like this (I don't know what the ints before the Students are, so let's just call it id):
typedef struct
{
int age;
int phoneNumber;
} Student;
typedef struct
{
int id;
Student student;
} StudentAndId;
typedef struct
{
int id;
StudentAndId students[];
} People;
Note the lack of size in the array inside People. Now you do this:
People *p = malloc(sizeof(People) + sizeof(StudentAndId[NUM_OF_PEOPLE]));
Then you can access students inside p as if it was an array of NUM_OF_PEOPLE elements.
Remember to compile with C99 (or C11) support. With gcc that would be -std=c99 or -std=gnu99.
This will allocate memory for storing the date but how you access it depends on how you store date. using C pointers you can store and access data using this structure and allocation but accessing the members will not be direct. it will involve pointer arithmetic. So better to use other structure if possible. If using this way of allocation then you need to do pointer arithmetic to get the next elements.
Try this:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int age;
int phoneNumber;
} Student;
typedef struct
{
int id;
int student[1];
} People;
#define NUM_OF_PEOPLE 10
int main()
{
People *p = malloc(sizeof(People) + sizeof(int) * NUM_OF_PEOPLE + sizeof(Student) * NUM_OF_PEOPLE);
int* id = (int*)(p+1);
Student* s = (Student*)(id+NUM_OF_PEOPLE);
printf("Size of People : %d\n", sizeof(People));
printf("p points to : %p\n", p);
printf("id points to : %p\n", id);
printf("s points to : %p\n", s);
}
Here's a sample output:
Size of People : 8
p points to : 0x80010460
id points to : 0x80010468
s points to : 0x80010490
You may want to add the id field to your Student data structure, e.g.:
typedef struct {
int id;
int age;
int phoneNumber;
} Student;
Then, you can define a structure having a fixed header (in this case, this can be the number of students), followed by a variable-sized array of Students:
#define ARRAY_OF_ANY_SIZE 1
typedef struct {
int count;
Student students[ARRAY_OF_ANY_SIZE];
} People;
This blog post explains this technique of having "arrays of size 1", including a discussion of the alignment problem.
I won't repeat the original blog post code here. Just consider that you can use the portable offsetof() instead of the Windows-specific FIELD_OFFSET() macro.
As a sample code, you may want to consider the following:
#include <stdio.h> /* For printf() */
#include <stddef.h> /* For offsetof() */
#include <stdlib.h> /* For dynamic memory allocation */
typedef struct {
int id;
int age;
int phoneNumber;
} Student;
#define ARRAY_OF_ANY_SIZE 1
typedef struct {
int count;
Student students[ARRAY_OF_ANY_SIZE];
} People;
int main(int argc, char* argv[]) {
People* people;
const int numberOfStudents = 3;
int i;
/* Dynamically allocate memory to store the data structure */
people = malloc(offsetof(People, students[numberOfStudents]));
/* Check memory allocation ... */
/* Fill the data structure */
people->count = numberOfStudents;
for (i = 0; i < numberOfStudents; i++) {
people->students[i].id = i;
people->students[i].age = (i+1)*10;
people->students[i].phoneNumber = 11000 + i;
}
/* Print the data structure content */
for (i = 0; i < people->count; i++) {
printf("id: %d, age=%d, phone=%d\n",
people->students[i].id,
people->students[i].age,
people->students[i].phoneNumber);
}
/* Release the memory allocated by the data structure */
free(people);
return 0;
}
Output:
id: 0, age=10, phone=11000
id: 1, age=20, phone=11001
id: 2, age=30, phone=11002
I need to execute a function that returns array of a specified struct with variable length. Then I should loop through the returned array.
example struct :
typedef struct student {
int id;
char *name;
int grade;
} Student;
function prototypes 1 :
Student *students;
students = findStudentByGrade(int grade);
function prototypes 2 :
Student *students;
int retval = findStudentByGrade(&students, int grade);
I am bit confused on above methods. How can correctly define a array of struct? call function ? and loop through it untill end? Can some one help me please.
You can do this in this way. This code is working. I tested in CodeLite.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student {
int id;
char *name;
} Student;
Student *findStudent(int *asize, const int grade);
int main(void)
{
Student *stds;
int asize = 0;
stds = findStudent(&asize, 5);
int i;
for (i = 0; i < asize; i++) {
printf("ID : %i\n", stds[i].id);
}
return 0;
}
Student *findStudent(int *asize, const int grade)
{
struct student *stds = malloc(sizeof(struct student) * 3);
stds[0].id = 10;
stds[1].id = 20;
stds[2].id = 40;
*asize = 3;
return stds;
}
Get the array of struc as returned statement and pass an int variable with argument list to get the size back and simply loop through using a for loop. Or else you will find problem in looping. It is more easy to get the array size from the function which create the array.
I mean this is quite a basic question, but:
Defining array of your structures would look like:
int size = ...;
Student *students = (Student*) malloc(sizeof(Student) * size);
Then just pass that to the function (both size and the array) and then just loop until i < size.
Ofcourse, don't forget to:
free(students);
at the end.
I am trying to get familiar with struct and pointers in C and I am running into a bunch of syntax errors like "missing ';' before type", "missing ')' before type" and "undeclared identifier: 'i'". Everything seems fine, I know i is declared and I don't seem to be missing any ; or ).
#include <stdlib.h>
#include <stdio.h>
#pragma warning(disable: 4996)
struct Room;
struct House;
struct Room
{
float width;
float length;
float height;
char *name;
};
struct House
{
char *address;
struct Room *rooms[10];
};
int main(int argc, char* argv[])
{
struct House h;
h.address = "10 Palace Road";
for(int i = 0; i < 10; i++) // 6 errors occur here
{
h.rooms[i] = NULL;
}
struct Room hall;
hall.width = 10;
hall.length = 12;
hall.height = 9;
hall.name = "Hall";
h.rooms[0] = &hall;
printHouse(h);
system("PAUSE");
return 0;
}
void printHouse(struct House house)
{
printf(house.address);
printf("\n\n\n");
for (int i=0; i<10; i++)
{
if (house.rooms[i] != NULL)
{
struct Room r = *house.rooms[i];
printf("Room # %d: %s", i+1, r.name);
}
}
}
printf(house.address);
should be
printf("%s",house.address);
Also you must declare your function printhouse, since you have defined it after main.
#include <stdlib.h>
#include <stdio.h>
#pragma warning(disable: 4996)
struct Room; //you don't need this
**EDIT**
struct House
{
char *address;
struct Room *rooms[10];
};
void printHouse(struct House house);
Declare House first then the function.
int i;
for (i = 0; i < 10; i++){
//...
}
In earlier versions of C, you cannot declare I inside a loop.
Some versions of C compilers do not allow 'i' to be declared in the loop. Try declaring 'i' separately at the beginning of 'main()'. That should work.
I'm trying to use a queue in my program, but it won't compile and I don't know why. The relevant part of the code is as follows.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#ifndef CUSTOMER
#define CUSTOMER
typedef int bool;
int r;
typedef struct{
int arrival;
int leaving;
} Customer;
static const int MAX_LENGTH = 100;
typedef struct{
int head;
int length;
Customer customer[MAX_LENGTH];
} CustomerLine;
void initializeQueue(CustomerLine* queue)
{
(*queue).head = 0;
(*queue).length = 0;
}
bool hasNext(CustomerLine* queue)
{
return (*queue).length > 0;
}
bool isFull(CustomerLine* queue)
{
return (*queue).length == MAX_LENGTH;
}
bool enqueue(CustomerLine* queue, Customer* customer)
{
if(isFull(queue))
return 0;
int index = ((*queue).head + (*queue).length) % MAX_LENGTH;
(*queue).customer[index] = *customer;
(*queue).length++;
return 1;
}
Customer* dequeue(CustomerLine* queue)
{
if(!hasNext(queue))
return 0;
Customer* result = &(*queue).customer[(*queue).head];
(*queue).length--;
(*queue).head = ((*queue).head + 1) % MAX_LENGTH;
return result;
}
The error says "Variably Modified 'customer' at file scope" I am a beginner at programming and just doing this is starting to get beyond my abilities so any help would be very much appreciated.
The line
static const int MAX_LENGTH = 100
is the problem. Replace it with
#define MAX_LENGTH 100
See why here and more explanations here or here or again here.
Furthermore:
You need an #endif after the #ifndef.
You need a main function somewhere.
In C, const means read-only, not constant and usable just like a macro. You cannot use a variable to specify the dimension of an array as you do here:
static const int MAX_LENGTH = 100;
typedef struct{
int head;
int length;
Customer customer[MAX_LENGTH]; /* Wrong. MAX_LENGTH is not a compile time constant. */
} CustomerLine;