I would like to pass the struct array as an argument of the print function and then acces its members for printing. Why do I get a pointer error when I do not pass any pointers?
in main.c:
struct city {
double longitude;
double latitute;
char name[buf_size];
};
int numCitToRead = 10;
struct city cities[25];
printCities(&numCitToRead, cities);
Note: The Struct array gets initialised in a file parsing function. It is always 25 fields long, but if numCitToRead is 10, Only 10 fields will be filled
int printCities(int* t_numCitToRead, struct city t_cities[25]) {
for (unsigned short i = 0; i < *t_numCitToRead; i++) {
printf("\n\n\tCity %d: ", i+1);
printf("\nname:\t\t%s", t_cities[i].name);
printf("\nlongitude:\t%f", t_cities[i].longitude);
printf("\nlatitude:\t%f", t_cities[i].latitute);
}
return 0;
}
I hope someone can help me!
Greetings
Have modified the code and its working now.
let's try it:
#include <stdio.h>
struct city {
double longitude;
double latitute;
char *name;
};
int printCities(int* t_numCitToRead, struct city t_cities[25]) {
for (unsigned short i = 0; i < *t_numCitToRead; i++) {
printf("\n\n\tCity %d: ", i+1);
printf("\nname:\t\t%s", t_cities[i].name);
printf("\nlongitude:\t%f", t_cities[i].longitude);
printf("\nlatitude:\t%f", t_cities[i].latitute);
}
return 0;
}
int main() {
int numCitToRead = 10;
struct city cities[25];
// create dummy data
for(int i =1; i<=25; i++)
{
cities[i-1].name = "name";
cities[i-1].longitude = 10 * i;
cities[i-1].latitute = 10 * 20;
}
printCities(&numCitToRead, cities);
return 0;
}
Thanks!
Thanks to everyone for the great support and helpful comments and suggestions.
After adjusting a few different things which were pointed out by people in this thread, it finally compiled succesfully.
The things I adjusted were:
inlcuded the header file to the city struct data type definition in the printFunctions file
initialized the struct to resolve pointer errors
Thanks for the great feedback and comments / suggestions.
Have a nice day!
Related
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct card_t{
char value;
char suit[50];
} card_t;
card_t draw(){
card_t karta;
int v = (rand() % 13)+2;
int s = (rand() % 4)+1;
if(v<=9){
karta.value = v +'0';
}else{
if (v==10)
karta.value='T';
if (v==11)
karta.value='J';
if (v==12)
karta.value='Q';
if (v==13)
karta.value='K';
if (v==14)
karta.value='A';
}
if (s==1)
strcpy(karta.suit, "of Spades");
if (s==2)
strcpy(karta.suit, "of Hearts");
if (s==3)
strcpy(karta.suit, "of Diamonds");
if (s==4)
strcpy(karta.suit, "of Clubs");
return karta;
}
void face_up(card_t deck[],int size){
for(int i=0;i<=size;i++){
printf("%c %s\n",deck[i].value ,deck[i].suit);
}
}
int main()
{
int size;
card_t *deck;
deck = malloc(100*sizeof(char));
card_t karta;
karta=draw();
for (int i=0; i<100 ; i++){
deck[i]=karta;
if(strcmp(deck[i].suit,"of Spades")==0 && deck[i].value=='A'){
size=i;
break;
}
karta=draw();
/*THIS ONE*/printf("%c %s\n",deck[i].value ,deck[i].suit);
}
face_up(deck,size);
free(deck);
return 0;
}
If I remove the line marked with /THIS ONE/ , the function face_up won't print anything , but if the line is there it works. Any ideas ? Tried it several times and its the same thing .
I would get double print if i leave it there , which i dont need.
Im sorry for the bad code / formatting but i am kinda new to this and yeah ...
Thank you for your help in advance.
This line here deck = malloc(100*sizeof(char)); allocates memory on the heap to store an array of 100 chars. What you want to do, is to allocate an array of 100 card_t. To do this just replace the statement with the following one:
deck = malloc(100*sizeof(card_t));
I looking for a answer and can't find nowhere. I hope you'll help me. I write a simple app which include struct with a name of worker and . But when i want to change value of name i can't do it. I don't know why. Maybe you can't help me or you know another ways to do it? My code:
struct workers {
char name[256]="no";
int pay=-1;
};
void addOne(struct workers work[20]) {
char name[256];
int i=0;
for (i = 0; work[i].name != "no"; i++) {}
printf_s("Enter name of worker: ");
scanf_s("%s", &name);
//-----error here-----
work[i].name = name;
}
int main()
{
int i;
struct workers work[20];
for (i = 0;i < 20; i++) {
if (work[i].name != "no") {
work[i].pay = 100 * i;
}
}
for (i = 0; i < 20; i++) {
printf_s("%s\t%d\n", work[i].name, work[i].pay);
}
return 0;
}
work[i].name = name;
The above line is where the problem is.
Change as below:
snprintf( work[i].name, sizeof(work[i].name), "%s", name);
What you have done is trying to change the base pointer of the array and not the name.
Also there were few more errors in the code, pls resolve them.
It is not possible to set default values to structure as you have done in C.
You have to write code to init each array instance name variable with "no" in a loop and then use one of the string comparison functions to compare the strings. And then call your addOne.
I have tried to create a CD struct like :
typedef struct
{
char* nameCD;
int yearOfpublication;
song* listOfSongs;
int priceCD;
int numberOfSongs;
} CD;
and I have a song struct :
typedef struct
{
char* nameSong;
char* nameSinger;
int lenghtOfSong;
} song;
void SongInput(song *psong, CD *pcd)
{
pcd->numberOfSongs++;
pcd->listOfSongs = (song*)malloc(pmcd->numberOfSongs*sizeof(song));
// here all the code that update one song..
but what should I write to update the next song?
how do I change it into an array which update the number of the songs and how can I save all the songs?
I tried this :
printf("Enter lenght Of Song:");
scanf("%d", &psong->lenghtOfSong);
but I don't understand the pointers..
and how to update the next song?
}
void CDInput(CD *pcd)
{
int numberOfSongs = 0;
//here all the other update of cd.
//songs!!!!!!!!!!!!!!!!!!!!!!!!!!!!
pcd->numberOfSongs = 0;
pcd->listOfSongs = (song*)malloc(numberOfSongs*sizeof(song));
}
Do I need to write anything else?
void CDInput(CD *pcd)
{
int i;
//...
printf("Enter number Of Song:");
scanf("%d", &pcd->numberOfSongs);
pcd->listOfSongs = (song*)malloc(pcd->numberOfSongs*sizeof(song));
for(i = 0; i < pcd->numberOfSongs; ++i){
SongInput(&pcd->listOfSongs[i]);
}
//...
}
It depends on if you want to write the structure once completely or you really want to add one item.
For the first case, please refer to BLUEPIXY's answer, for the second one, thigs are slightly more complicated.
bool add_song(song *psong, CD *pcd)
{
song* newone = realloc(pcd->listOfSongs, (pmcd->numberOfSongs+1)*sizeof(song));
if (!newone) {
// return and complain; the old remains intact.
return false; // indicating failure.
}
// now we can assign back.
pcd->listOfSongs = newone;
newone[pcd->numberOfSongs++] = *psong;
return true; // indicating success.
}
Note: Fixed (decription at bottom)
For some reason the following code:
(*p_to_array)[m_p->number_of_match_positions] = (*p_to_temp_array)[k];
where the types are:
match_pos_t (*p_to_array)[];
match_pos_t (*p_to_temp_array)[];
int number_of_match_positions;
int k;
BTW: match_pos_t is a struct:
typedef struct match_pos
{
char* string;
long match_position;
}match_pos_t;
causes a 'syntax error before '(' error'
This error does not occur if this code replaced with other code.
Could someone give me an idea of why this is causing a syntax error, and how I should fix this problem?
Entire relevant code:
typedef struct match_pos
{
char* string;
long match_position;
}match_pos_t;
typedef struct match_positions
{
int number_of_match_positions;
match_pos_t (*match_positions)[];
}match_positions_t;
typedef struct search_terms
{
int number_of_search_terms;
char* search_terms[];
}search_terms_t;
int BMH_string_search(char* search_string, char* file_string, match_positions_t* match_positions)
{
return 0;
}
int determine_match_pos(search_terms_t** s_terms, char* file, match_positions_t* m_p)
{
int i,j,k;
match_positions_t* temp_m_p;
i=0;
/* s_terms is a null terminated data structure */
while((*s_terms+i) != NULL)
{
for(j=0; j<(*s_terms+i)->number_of_search_terms; j++)
{
/* search for the string positions */
BMH_string_search((*s_terms+i)->search_terms[j], file, temp_m_p);
/* load out search positions into the return array */
if(temp_m_p->number_of_match_positions != 0)
{
int total_m_ps = m_p->number_of_match_positions + temp_m_p->number_of_match_positions;
m_p->match_positions = (match_pos_t (*)[])realloc(m_p->match_positions, sizeof(match_pos_t)*total_m_ps);
k = 0;
for( ; m_p->number_of_match_positions<total_m_ps; m_p->number_of_match_positions++)
{
(*(m_p->match_positions))[m_p->number_of_match_positions] = (*(temp_m_p->match_positions))[k];
k++;
}
}
free(temp_m_p);
}
i++;
}
return 0;
}
It appears I have been rather stupid. An extra set of parenthesis around the values being referenced does the trick (question code has been updated with fix):
Original:
(m_p->*match_positions)[m_p->number_of_match_positions] = (temp_m_p->*match_positions)[k];
Fixed:
(*(m_p->match_positions))[m_p->number_of_match_positions] = (*(temp_m_p->match_positions))[k];
If anyone has an explanation, though, about why the first is incorrect, rather than the second, it would be nice to hear though, as I thought that
object->*object2
was the same as
*(object->object2)
Is this correct or is there some c definitions that I am missing out on here?
I thought that object->*object2 was the same as *(object->object2)
No, in C, the . and -> operators expect an identifier as their right operand. The .* and ->* operators don't exist in C, you have to spell out *(structure.member) or *(structure_ptr->member) manually.
I have my code below that consits of a structure, a main, and a function. The function is supposed to display two parameters that have certain values, both of which point to the same structure.
The problem I dont know how to add the SECOND parameter onto the following code :
#include<stdio.h>
#define first 500
#define sec 500
struct trial{
int f;
int r;
float what[first][sec];
};
int trialtest(trial *test);
main(){
trial test;
trialtest(&test);
}
int trialtest(trial *test){
int z,x,i;
for(i=0;i<5;i++){
printf("%f,(*test).what[z][x]);
}
return 0;
}
I need to add a new parameter test_2 there (IN THE SAME FUNCTION) using this code :
for(i=0;i<5;i++){
printf("%f,(*test_2).what[z][x]);
How does int trialtest(trial *test) changes ?
and how does it change in main ?
I know that I should declare test_2 as well, like this :
trial test,test_2;
But what about passing the address in the function ? I do not need to edit it right ?
trialtest(&test); --- This will remain the same ?
So please, tell me how would I use test_2 as a parameter pointing to the same structure as test, both in the same function..
Thank you !!
Please tell me if you need more clarification
I think that this is your homework, so I'll just write a different function that may give you an idea of what (I think) you need to do. I read that you don't want to change the trail_test parameter list, so I stuck with a similar parameter list.
struct thing {
/* put some stuff here */
};
typedef struct thing thing; /* because this is C, not C++ */
int how_many_things(thing * thing_list);
int main(void) {
int i;
thing * a;
int count_init = random(); /* let's surprise ourselves and make a random number of these */
count_init %= 128; /* but not too many or it might not work at all */
a = malloc(count_init*sizeof(things)+1);
for (i = 0; i < count_init; i++) {
thing_init(&(a[i]));
}
make_illegal_thing(&(a[count_init]) ); /* like '\0' at the end of a string */
printf("There are %i things in the list\n", how_many_things(a) );
return 0;
}
/* This is very similar to strlen */
int how_many_things(thing * a) {
int count = 0;
while (is_legal_thing(a) ) {
a++;
count++;
}
return count;
}