Dynamic Array of Structures in C - c

I'm trying to create an array of structures, but I'm not sure how to proceed with declaring an array and mallocing it. Here is the code I have so far:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_STRING 128
typedef char String[MAX_STRING]
typedef struct {
String Name; //Name of the person
String Best; //Name of the best friend
} Names;
int main(void) {
}
This is an exercise I'm trying to do and the end product should be like this: HERE

#include <stdlib.h>
#include <stdio.h>
#define N 3
typedef struct
{
char* Name; //Why complicate things using a string?
char* Best;
}Names;
int main(void)
{
int i;
//Create an array of pointers.
//Each element of the array is a pointer to a struct "Names"
Names** data = malloc(N*sizeof(Names*));
//data[i] is a array element which points to a single struct "Names".
//Dynamically allocate memory for each struct
for(i=0;i<N;i++)
{
data[i] = malloc(sizeof(Names));
}
//Rest is your assignment
data[0]->Name = "aaaa";
data[0]->Best = "bbbb";
data[1]->Name = "cccc";
data[1]->Best = "dddd";
data[2]->Name = "eeee";
data[2]->Best = "ffff";
for(i=0;i<N;i++)
{
printf("%s\t%s\n",data[i]->Name,data[i]->Best);
}
}

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define MAX_STRING 128
#define NUMBER_OF_STRUCTURES_IN_ARRAY 10
typedef char String[MAX_STRING]
typedef struct {
String Name; //Name of the person
String Best; //Name of the best friend
} Names;
int main(void)
{
int rCode=0;
Names *names_A = NULL;
int index;
names_A = malloc(sizeof(*names_A) * NUMBER_OF_STRUCTURES_IN_ARRAY);
if(NULL == names)
{
rCode=ENOMEM;
fprintf(stderr, "Error: malloc() failed\n");
goto CLEANUP;
}
for(index=0; index < NUMBER_OF_STRUCTURES_IN_ARRAY; ++index)
{
strcpy(names_A[index].Name, "Some Name");
strcpy(names_A[index].Best, "Another Name");
}
CLEANUP:
if(names_A)
free(names_A);
return(rCode);
}

Related

C - How to give a name to a struct dynamically

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

C programming : Creating substring

I'm new in C and I need some explanation on what I am doing wrong.
I'm trying to iterate over a string and find the first '\' then make a substring from that place in the array.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
struct info{
char* name;
char* type;
char* path;
};
struct info user1;
char* a = "/home/users/user1";
for (int i = strlen(a) ; i < 0 ; i--) {
printf("%d",i);
if(strcmp(a[i],'/')==0){
strncpy(a,user1.name,i);
break;
}
}
return 0;
}
There are many errors I will explain them one by one. The code will be something like this.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
struct info{
char* name;
char* type;
char* path;
};
struct info user1;
user1.name = malloc(40);
if( user1.name == NULL){
fprintf(stderr, "%s\n","Error in malloc" );
exit(1);
}
const char* a = "/home/users/user1";
for(int i = strlen(a) -1; i >= 0 ; i--) {
if(a[i]=='/'){
strncpy(user1.name,a+i+1,i);
user1.name[i]='\0';
break;
}
}
printf("%s\n",user1.name );
free(user1.name);
return 0;
}
Things you did wrong
There was no memory allocated to name it was simply an uninitialized pointer. Here we have allocated memory to it.
Second thing, strcmp as the name suggests compares null terminated char array not char-s. It can be done with simple == operator.
The copy part is modified to only copy the user name part nothing else. That's why we have incremented the pointer to point to the correct position.
You forgot to check the return value of malloc and then you should free the allocated memory.
Also you can't modify a string literal because it stays in non-modifiable portion of the memory.
try this,
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
struct info{
char* name;
char* type;
char* path;
};
struct info user1;
user1.name = malloc(10);
char* a = "/home/users/user1";
int len=strlen(a);
for (int i = 0; i < len; i++) {
printf("%d",i);
if(a[i]=='/'){
strncpy(user1.name,a+i+1,i);
user1.name[i]='\0';
break;
}
}
return 0;
}

Filling in data for a struct that holds an array of of pointers to a different struct

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);
}

c fwrite() writing to a file with only one of the struct variable?

This function is supposed to get a parameter as the pointer of a file and put all file into the struct anagram, then write it to another file. Right now the data only contains a.word, but it suppose to containst a.sorted too? I have check the a.sorted using printf
and it printf out the correct data, but why its not writing to the data file?
It still cant get the a.sorted even if i increase the count of the frwite
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "anagrams.h"
#define SIZE 80
//struct
struct anagram {
char word[SIZE];
char sorted[SIZE];
};
void buildDB ( const char *const dbFilename ){
FILE *dict, *anagramsFile;
struct anagram a;
//check if dict and anagram.data are open
errno=0;
dict= fopen(dbFilename, "r");
if(errno!=0) {
perror(dbFilename);
exit(1);
}
errno=0;
anagramsFile = fopen(anagramDB,"wb");
char word[SIZE];
char *pos;
int i=0;
while(fgets(word, SIZE, dict) !=NULL){
//get ripe of the '\n'
pos=strchr(word, '\n');
*pos = '\0';
strncpy(a.word,word,sizeof(word));
//lowercase word
int j=0;
while (word[j])
{
tolower(word[j]);
j++;
}
/* sort array using qsort functions */
qsort(word,strlen(word), 1, charCompare);
strncpy(a.sorted,word,sizeof(word));
//printf(a);
fwrite(&a,1,strlen(word)+1,anagramsFile);
i++;
}
fclose(dict);
fclose(anagramsFile);
}
it suppose to contains data with a.sorted for example "10th 01ht"
data:
fwrite(&a,1,strlen(word)+1,anagramsFile); should have been fwrite(a.sorted,1,strlen(a.sorted)+1,anagramsFile); I assume the declaration of sorted as char sorted[SOME_LEN];

Instantiations for structs in C?

So I'm trying to learn C right now, and I have some basic struct questions I'd like to clear up:
Basically, everything centers around this snippet of code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN 127
const char* getName(const Student* s);
void setName(Student* s, const char* name);
unsigned long getStudentID(const Student* s);
void setStudentID(Student* s, unsigned long sid);
int main(void) {
Student sarah;
const char* my_name = "Sarah Spond";
setName(&sarah, my_name);
printf("Name is set to %s\n", sarah.name);
}
typedef struct {
char name[MAX_NAME_LEN + 1];
unsigned long sid;
} Student;
/* return the name of student s */
const char* getName (const Student* s) { // the parameter 's' is a pointer to a Student struct
return s->name; // returns the 'name' member of a Student struct
}
/* set the name of student s
If name is too long, cut off characters after the maximum number of characters allowed.
*/
void setName(Student* s, const char* name) { // 's' is a pointer to a Student struct | 'name' is a pointer to the first element of a char array (repres. a string)
int iStringLength = strlen(name);
for (i = 0; i < iStringLength && i < MAX_NAME_LEN; i++) {
s->name[i] = name[i];
}
}
/* return the SID of student s */
unsigned long getStudentID(const Student* s) { // 's' is a pointer to a Student struct
return s->sid;
}
/* set the SID of student s */
void setStudentID(Student* s, unsigned long sid) { // 's' is a pointer to a Student struct | 'sid' is a 'long' representing the desired SID
s->sid = sid;
}
However, when I try and compile the program, I get a bunch of errors saying that there's an "unknown type name Student". What am I doing wrong?
Thanks!
Move the type definition for Student - the typedef .. right after #define MAX_NAME_LEN 127, i.e. before it's being referenced.
You need to move the declaration of the Student struct above the first time it is referenced by other code - otherwise those functions will not know what it is.
Struct declarations need to be defined before you use them , so you need to move your Student
As cnicutar said, move the typedef - the reason for this is that the type must be known before it's used. Alternatively, you can forward declare the type.
> Move the typedef .. right after #define MAX_NAME_LEN 127, i.e. before
> it's being used.
OR, if you want to keep your definition after, and if you are ready to use a pointer to Student, you can:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN 127
// forward declare Student ici
struct Student;
//...
// in main, use a pointer to student
int main(void) {
Student *sarah; // Changed to pointer
const char* my_name = "Sarah Spond";
setName(sarah, my_name); // Pass the pointer instead of reference
printf("Name is set to %s\n", sarah->name); // Use the pointer
//....
delete sarah; // delete object when done
}
// Change struct decl to the following // can't explain the diff yet
struct Student {
char name[MAX_NAME_LEN + 1];
unsigned long sid;
};
A basic structure of a C program is:
//======DOCUMENT SECTION=========
//File:test.c
//Author:
//Description:
//...
//================================
//====INCLUDE SECTION=============
#include "lib1"
#include <lib2>
//================================
//========DEFINITIONS SECTION=====
#define TRUE 1
#define FALSE 0
//================================
//========STRUCTURES SECTION======
struct P{
};
//================================
//========TYPEDEFS SECTION========
typedef *P P;
//================================
//========FUNCTION HEADERS========
void foo1(...);
int foo2(...,...,...);
//================================
//=========GLOBAL VARIABLES=======
int GLOBAL_INT;
float GLOBAL_FLOAT;
//================================
//=====MAIN FUNCTION DEFINITION===
void main(void)
{
...
...
...
}
//=================================
//======FUNCTIONS DEFINITION======
void foo1(...)
{
}
int foo2(...,...,...)
{
}
//================================
A main function is where a C program starts. A main function also typically has access to the command arguments given to the program when it was executed.
Usually you have got:
int main(void);
int main();
int main(int argc, char **argv);
int main(int argc, char *argv[]);

Resources