What am i doing wrong in this code? - c

#include <stdio.h>
main()
{
typedef struct{
char *name;
int age;
}person[5];
int i;
for (i=0;i<5;i++){
printf ("name:");
scanf("%s",person[i].name);
printf("\nage:");
scanf("%d",&person[i].age);}
for (i=0;i<5;i++){
printf ("person:%d",i);
printf ("name:%s",person[i].name);
printf ("age:%d",person[i].age);
}
}
this is the sample program i have. But while compiling i keep getting the error "expected expression before person in line 10,12,16 and 17? What am i doing wrong?

To fix the syntax error, remove the typedef keyword (you're trying to declare a variable, not a type).
Better yet, change to:
typedef struct{
char *name;
int age;} Person;
Person person[5];
Also, the following is wrong:
scanf("%s",person[i].name);
You need to first allocate memory for person[i].name (for example, using malloc()).
Lastly, the %s format specifier in the following line is not correct:
printf ("age:%s",person[i].age);

person is a type, not an object. You cannot "scanf() into a type: person".
I'd simply remove the typedef and just leave the struct definition outside the body of main; and create an object inside
struct person { /* ... */ };
int main(void) {
struct person person[5];
/* ... */
return 0;
}

Related

structure identifier is not defined even though it is

I have a school project where I have to make my structures and functions in a .h header file.
I've created my structure but cannot use any of the variables within it as whenever I call it it highlights the structure name and tells me its not defined even though it clearly is in my structure and doesn't highlight or give me any syntax errors.
#include <stdio.h>
typedef struct test1 {
int array1[3];
int array2[3];
};
int main(void) {
scanf_s(" %d %d", &test1.array1[1], &test1.array2[1]);
}
I have tried using typedef with and without and its the same result. if I create individual variables outside the structure I get no issues so i believe its some issue with how I'm creating my structures but I don't know what the issue is.
The use of typedef makes me think that you actually want to define a type named test1. Move the name to after the struct:
#include <stdio.h>
typedef struct {
int array1[3];
int array2[3];
} test1; // now a name you can use
You then need to create an instance of test1 to be able to use it with scanf_s:
int main(void) {
test1 t1; // `t1` is now a `test1` instance
scanf_s(" %d %d", &t1.array1[1], &t1.array2[1]);
// ^^ ^^
}
You declared type specifier struct test1 (and moreover the typedef declaration does not even declare a typedef name for the type specifier struct test1)
typedef struct test1 {
int array1[3];
int array2[3];
};
But the call of scanf_s
scanf_s(" %d %d", &test1.array1[1], &test1.array2[1]);
expects objects. test1 is not an object. This name is not even declared.
You could write for example
struct test1 test1;
scanf_s(" %d %d", &test1.array1[1], &test1.array2[1]);

C typedef struct not printing char str

So this structure is per a class assignment, so while there are easier ways to do this, this is the way I am supposed to do it. So structure needs to remain intact. That said, I can not make this print my line.
In Geany it will say it compiled successfully, but when I go to run it in console the char string is 'u????' instead of the string. I'm fairly new to structures in C so I am not really sure what this thing is doing. I have tried using brackets to establish the length of the char array like your supposed to with C, but it would then tell me to remove them. Any help would be greatly appreciated.
#include <stdio.h>
typedef struct {
unsigned char name;
} MY_DATA;
void name (MY_DATA *n)
{
n->name = *"Kyle";
}
int main (void)
{
MY_DATA data;
name (&data);
printf ("My name is %s\n", &name);
}
I know, that it's already solved, but here is the working code. Also name doesn't need to be unsigned.
#include <stdio.h>
typedef struct {
char *name;
} MY_DATA;
void name (MY_DATA *n)
{
n->name = "Kyle";
}
int main (void)
{
MY_DATA data;
name (&data);
printf ("My name is %s\n", data.name);
}

Trying to print out a data type of a struct encapsulated in another struct

i was just wondering if anyone knew how to resolve an issue i'm getting when trying to print out a value of a data type "char []" of a struct that's encapsulated within another struct. Any advice would be appreciated as i've spent hours trying to resolve this issue already. Thanks in advance,
the error im gettinng is warning: (format '%s' expects argument of type 'char *', but argument 2 has type 'int')
struct food_stuff
{
char name [30];
int calories;
int foodtype;
int price;
};
typedef enum food_groups food_groups;
struct food_plan_item
{
food_stuff fs;
int qty;
};
typedef struct food_plan_item food_plan_item;
void print_food_line_items(food_plan_item *fpi)
{
for(int i =0 ; i<fpi_count;i++)
{
printf("%s", *(fpi+fpi_count)->fs.name);
}
}
You have an extra dereference in the line
printf("%s", *(fpi+fpi_count)->fs.name);
fpi->fs.name returns a char * pointer; *fpi->fs.name returns the first char of the array, which is a value (casts to int) not a pointer.
If you have the following structure definitions:
typedef struct
{
char name[30];
int calories;
int foodtype;
int price;
} food_stuff;
typedef struct
{
food_stuff fs;
int qty;
} food_plan_item;
You can access the fields of a food_plan_item structure like this:
food_plan_item fpi;
food_plan_item *pFpi = &fpi;
fpi.qty;
fpi.fs.name[0];
fpi.fs.calories;
fpi.fs.foodtype;
fpi.fs.price;
pFpi->qty;
pFpi->fs.name[0];
pFpi->fs.calories;
pFpi->fs.foodtype;
pFpi->fs.price;
The first one shows accessing a structure directly. The second shows accessing a structure through a pointer.
*(fpi+fpi_count).fs.name i guess

Sub-scripted value is neither array nor pointer

So I am trying to make a simple program which opens up a text file, reads the number of students that the file contains, their first names, last names and student numbers, and stores values in variables, and then finally returns a pointer to an array of those student objects. My code is as follows: -
#include <stdio.h>
#include <stdlib.h>
struct student
{
double studentNumber;
char *firstName;
char *lastName;
};
struct student *readStudentRecordFile(char *fileName, int *numOfStudents)
{
int i;
struct student a;
FILE *fp;
fp=fopen(fileName,"r");
fscanf(fp,"%d",&numOfStudents);
for(i=0;i<*numOfStudents;i++)
{
fscanf(fp, "%s" "%s" "%f", a[i].firstName,a[i].lastName,&a[i].studentNumber);
}
fclose(fp);
}
int main(void)
{
int nStudents;
struct student *readArray;
readArray=readStudentRecordFile("hello.txt", &nStudents);
return 0;
}
The problem is that when I run the program, I get an error stating the sub scripted value is neither an array nor pointer. I am sort of new to this concept, so I am sort of don't understand what it means. If anyone can tell me what I am doing wrong, and how I can achieve the result that I want, I will be very great-full. Thank you.
In your program a is neither an array nor a pointer. It is of struct student type . You should declare a as an array of struct.
struct student a[SIZE];
a[i].firstName
This is array notation.
a.firstName
This is variable notation.
struct student a;
This is what you have. It's a variable.
struct student a[LEN];
This is what you need. It's an array.

syntax error before '[' token

Here is the code
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<pthread.h>
typedef struct std_thread
{
char name[20];
int hallno;
int empid;
char dept[5];
}std[5];
void *print(void *args)
{
struct std_thread *data=(struct std_thread *)args;
printf("My thread id is %ld\n",pthread_self());
printf("Thread %d is executing\n",args);
printf("Name\tHall No\tEmployee ID\tDepartment\n");
printf("--------------------------------------------------------");
printf("%s\t%d\t%d\t%s\n",data->name,data->hallno,data->empid,data->dept);
}
int main()
{
pthread_t th[5];
int empid=2020;
int hall=1;
char dept[2]="IT";
char *names[]={"dinesh","vignesh","pradeep","prasath","mohan"};
int t;
int i;
int status;
for(i=0;i<5;i++)
{
std[i].name=names[i]; //Getting error from this line
std[i].hallno=hall; //Error at this line
hall++;
std[i].empid=empid; //Error at this line
empid++;
std[i].dept=dept; //Error at this line
status=pthread_create(&th[i],NULL,print,(void *)&std[i]);
if(status)
{
printf("Error creating threads\n");
exit(0);
}
}
pthread_exit(NULL);
}
While compiling this code, I'm getting "syntax error before '[' token". What is the reason for this?
This declaration does not do what you think it does:
typedef struct std_thread
{
...
}std[5];
This declares a struct named std_thread, and then it creates a typedef named std to mean "an array of 5 struct std_thread objects".
You probably wanted one of these two definitions, in order to declare a global object named std as an array of 5 struct std_thread's:
typedef struct std_thread
{
...
} std_thread;
std_thread std[5];
// OR
struct std_thread
{
..
} std[5];
In the first case, we also create the typedef named std_thread as an alias for struct std_thread; in the second case, we do not.
Furthermore, as others have stated, you cannot copy character arrays by assignment. You must copy them using a function such as strcpy(3) or strncpy(3). When using strcpy, you must ensure that the destination buffer is large enough to hold the desired string. Also keep in mind that strncpy does not necessarily null-terminate its destination string, so use it with caution.
I don't think you mean to typedef up the top.
What you've written there makes std an equivalent type as five of the structs in an array, but then you use std as though it is itself an array.
Remove the word typedef from line five and it should be closer to working.
Use string copy function instead of assigning char array.
You are trying to copy a string using assignment:
std[i].name=names[i];
and
std[i].dept=dept;
that does not work. Use a strcpy or better strncpy instead.
You have a typo in:
std[i].empid=empdid; //Error at this line
You don't have a var named empdid.
This code:
typedef struct std_thread
{
char name[20];
int hallno;
int empid;
char dept[5];
} std[5];
declares the type std to be an array of 5 struct std_thread structures.
This code:
int main()
{
[...]
int i;
int status;
for (i = 0; i < 5; i++)
{
std[i].name = names[i];
assumes that std is a variable with array or pointer type.
You need to remove the keyword typedef to make the code consistent with the use of the variable.
Then you can start running into problems with string assignments where you need to use string copy functions, etc.

Resources