pointers and structures in c [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I can't figure out how to access a certain parameter inside the structs that I am forced to use. The function gets a hotel and a passport number of one of the guests, and returns the number of the room in which the guest is staying, or NOT_FOUND if the guest is not at the hotel.
struct Guest
{
char name[20];
int passportNumber;
};
struct Room
{
int roomNumber;
int numOfGuests;
struct Guest* allGuests;//the Guests staying in the room
};
struct Hotel
{
int maxRooms;
int numOfUsedRooms;
struct Room** allRooms;
//array of Room* with physical size 'maxRooms'.
//only the first 'numOfUsedRooms' (logical size)
//rooms points to a room,all other pointers are
//NULL
};
int findGuestByPassportNumber(struct Hotel,int);
int main()
{
int i=0,j;
struct Hotel Cucamber;
printf ("before\n");//check
Cucamber.allRooms[i,i]->allGuests[i].name={"Spongebob"};
printf ("after\n");//check
Cucamber.allRooms[i,i]->allGuests[i].passportNumber=1234567890;
printf("%s",Cucamber.allRooms[i]->allGuests[i].name);
return 0;
}
The program doesn't even run because code blocks says:expected expression before '{' token.

First of all, you should google things like "c pointer" and so on and look at some basic tutorials.
Second, please think about your problem a bit first. You want to do a search. So if you search, you don't just know where it is, else you wouldn't have to search in the first place. So this means you'll have to check every available guest, wether his passport number matches the one your looking for.
This is obviously a case for "brute force"-search; so you'll have to do some loops. (Pseudocode):
Int Desiredpassportnumber = 1837748
Char *Name = NULL;
for( int i = 0; i < YourHotel.numberofRooms; i++){
for(int j = 0; j < YourHotel.allRooms[i].numofGuests; j++){
if(YourHotel.allRooms[i].allGuests[j].passportnum == desiredpassportnumber){
Name = YourHotel.allRooms[i].allGuests[j].name
break
}
}
}
If(name== NULL){
//handle No match found
}
Else {
//handle match found
}
This pseudocode, you'll have to add some semicolons and lowercaps some stuff etc. But this should be the idea behind it I think.
Hope this helps you in understanding your problem. :-)
To understand pointers better you should really just google a bit.

Related

best way to write a function to return an array of String with limited size (char *x[MAX] vs char **x)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
What is the best way to write a function to return an array of String.
I use the following function:
void getOperatorNames(char *names[]) {
int i=0;
for(; i<MAX_OPERATORS; i++) {
names[i] = malloc(64 * sizeof(char));
strcpy(names[i], op[i].fname);
}
}
and call it :
char *MenuItems[MAX_OPERATORS];
getOperatorNames(MenuItems);
But when I use MenuItems in a function with argument char ** it rises an exception and I don't know what is the cause.
What is the difference between char *x[] and char **x? IMO they must be equal!!
EDITTED:
struct operator{
int id;
char fname[32];
char ename[32];
};
struct operator op[MAX_OPERATORS];
the operators is filled by random text.
One way is to pack the array and its size together in a super-struct, and avoid the nasty-sized functions arguments:
#include <stdio.h>
#include <stdlib.h>
#define MAX_OPERATORS 666
struct operators {
unsigned count;
struct operator{
int id;
char fname[32];
char ename[32];
} ops[MAX_OPERATORS];
} ;
struct operators * getops(void)
{
struct operators *ret;
unsigned uu;
ret = malloc (sizeof *ret);
if (!ret) return ret;
ret->count = MAX_OPERATORS;
for(uu=0; uu < ret->count; uu++) {
ret->ops[uu].id= uu;
sprintf(ret->ops[uu].fname, "f%2u", uu);
sprintf(ret->ops[uu].ename, "e%2u", uu);
}
return ret;
}
This is only the beginning, you can lateron make the array variable-sized (using malloc, or a VLA), but the interface would stay the same, and the caller would not need to know the value of MAX_OPERATORS, it only needs the ->count structure element. You could also reuse it for other tables, using different counts.

What could cause this pointer to be corrupted? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
First of all, this code is running without any issue on my linux desktop pc (x86_64) but on my Cyclone v (arm cpu/fpga), I have a segmentation fault because the value of the pointer is changing. The relevant line is the last one, during the for loop, the value of "layer->filename" is changing, it is correct during the first iteration (the address given by malloc) but it changes on the second one.
Basically, this bit of code is copying character from "buff" to "layer->filename", as you can see in the output file, the value of buff[i] is a valid character so it should not corrupt layer->filename.
If you have an idea of what could cause this issue, please let me know.
Thank you for your help.
typedef enum
{
CONV,
BN,
FC,
} layer_type;
typedef struct layer{
layer_type layer_type;
int shape[3];
char *filename;
} layer;
...
layer *layer=malloc(sizeof(layer));
char buff[30];
int i;
...
layer->filename = malloc(sizeof(char)*(n+1));
if(buff[0]=='b')
layer->layer_type=BN;
else if(buff[0]=='c')
layer->layer_type=CONV;
else
layer->layer_type=FC;
for(i=0; i<n ; i++)
*(layer->filename+i)=buff[i];
values of buff[i] and layer->name during the loop
Using this code
#include <stdio.h>
#include <stdlib.h>
typedef enum
{
CONV,
BN,
FC,
} layer_type;
typedef struct layer{
layer_type layer_type;
int shape[3];
char *filename;
} layer;
size_t test(size_t x) {
printf("%d\n", (int)x);
return x;
}
int main(void) {
layer *layer=malloc(test(sizeof(layer)));
return 0;
}
You can see that sizeof(layer) in the line
layer *layer=malloc(sizeof(layer));
is not the size of a structure but the size of a pointer.
This is because the name of variable is the same as the type name and the compiler treated layer in sizeof as the variable (pointer) name.
To avoid this and have it allocate the size of structure, you should change the name of type or variable to avoid confusion.
Dereferincing the pointer
layer *layer=malloc(sizeof(*layer));
also can solve this problem, but I think renaming is better.

Int doesn't work in struct [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
int doesn't seem to work with struct and I don't know why. I did the same thing as before and it worked but now it doesn't.
This is the main code.
int main()
{
struct elemente {
char *prod[20];
int cod[20];
int cant[20];
int pret[20];
};
struct elemente a[20];
int i,n=1,p[20];
char *val[20];
for(i=1;i<=n;i++){
puts("Numele produsului");
scanf("%s",&a[i].prod);
puts("Codul");
scanf("%i",&a[i].cod);
puts("Cantitatea");
scanf("%i",&a[i].cant);
puts("Pretul");
scanf("%i",&a[i].pret);
}
It works and I dont see it having problems.
This is where the problem is.
puts("Scrieti numele produsului");scanf("%s", &val);
for(i=1;i<=n;i++){
if(strcmp(val,a[i].prod)==0){
printf("Codul produsului: %i\n", a[i].cod);
printf("Cantitatea: %i\n", a[i].cant);
printf("Pretul: %i\n", a[i].pret);
//p[i]=a[i].cant*a[i].pret;
//printf("Valoarea totala a elementelor %i\n",p[i]);
}
}
The strcmp works fine. But it cannot find the integer numbers I have input with my scanf. It shows a strange code like "2303134". What did I do wrong?
Also as you can see I need to multiply 2 functions but CodeBlocks has problems with the * symbol. How can I fix this?
The problem is that your struct contains arrays of each element instead of a single one. This is also why the multiplication a[i].cant*a[i].pret won't compile, because you're attempting to multiply two int [20] instead of 2 int.
Since you create an array of struct elemente, you only need to input one element in each one:
struct elemente {
char prod[50];
int cod;
int cant;
int pret;
};
You would then change the scanf call to read in prod as follows to make sure you don't read more characters than the value can handle:
scanf("%49s",a[i].prod);
Also, be sure to check the return value of scanf to see whether a value was actually read in.
The strange code, in
printf("Codul produsului: %i\n", a[i].cod) case, is because you try to print the address of a[i].cod instead of the value of integer.
The easiest way to fix this is modify your struct to:
struct elemente {
char *prod[20];
int cod;
int cant;
int pret;
};
It seems there's no requirement to assign int arrays in your struct, int variables are sufficient.
After this modification,
p[i]=a[i].cant*a[i].pret;
printf("Valoarea totala a elementelor %i\n",p[i]);
should be ok to work.

return dynamic array of struct from function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How do I dynamically create an array of struct in a function in C?
The struct:
typedef struct Track {
char artist[LONGSTR];
char file[LONGSTR];
int id;
int isAlbum;
char name[LONGSTR];
int pos;
char title[LONGSTR];
int time;
} Track;
The function:
int
processplaylist (struct Track** tracks, char* resp)
{
//count the tracks to return
//allocate space for the resulting tracks
*tracks = mem_alloc (count * sizeof (struct Track));
//process each track
return count;
}
And the usage:
char playliststr[] = "file: some-mp3\nTitle: Dire Straits - Romeo And Juliet\nName: TheRadio\nPos: 0\nId: 12\nOK\n"
struct Track* tracks = NULL;
int count = mpd_processplaylist(&tracks, playliststr);
Within the function the tracks are nicely processed and upto the return statement tracks points to the right location to get to the tracks. Most questions I have seen are about arrays to values, not structs.
This answer returns an array of structs, but I would like to return the count (question of style) and return the array through the parameter.
What is going wrong? After the function returns, count has the right value and tracks is still NULL.
As the not so nice people pointed out by down voting the question, the question is too broad and vague. I apologize for that, I was desperate.
As the nice people in the comments confirmed, the code is correct. Even though the debugger showed that just before the return statement everything was OK and after returning to the usage it was not.
By commenting out code lines and logging a lot, there are two things to note.
Within the function, you must refer to the individual tracks as (*tracks + i) or, for example, (*(*tracks + i)).file. Indeed, not shown in the sample code. I had tried *(tracks + i), &tracks[i] and tracks + i, which in the debugger all seemed to work and did not cause immediate errors. I guess the code messed up memory that only came out after the return.
Outside the function, in the usage, you refer to the tracks as an array, as tracks[i] or, for example, tracks[i].file.
I hope that at least my answer helps.

Segmentation fault using char pointers in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
With my current implementation of code, I'm getting a segmentation fault that I think is caused by trying to store several char* in another char*. However, I don't know a way around this being fairly new to C. I'm in a GLUE Unix environment. The code compiles but does not fully execute.
Here's my method that I think is causing the issue.
int totalLogins = 0, selectedLogins = 0,dateIn[3], timeIn[3], dateOut[3], timeOut[3];
int latest = 0,earliest=30,loggedIn = 0, firstTime[7][3],firstDate[7][3],i;
char* user[12], firstUser[7][12];
bool first = true;
void checkAndSetEarliest(int day)
{
first = true;
for(i = 0; i < 3 && first; i++)
{
first = (timeIn[i]<firstTime[day][i]);
}
if(first)
{
for(i = 0; i < 3; i++)
{
firstTime[day][i] = timeIn[i];
firstDate[day][i] = dateIn[i];
}
printf("user = %s\n",user);
firstUser[day] = user;
}
}
timeIn[],firstTime[][],firstDate[][], and dateIn[] are all ints
firstUser[] and user[] are char*
I'm trying to edit the contents of firstUser with the value of user.
First, the way you are using user[] in printf, it is suppose to be a char array, not an array of pointer to char (what you have declared).
Secondly, firstuser is a 2d arrray and you are using it as a 1d array.
You really need to show the definition of the variables this function uses. Fair chance that last line should be changed to:
strcpy( FirstUser[day], user );

Resources