I’m getting the error «expected expression before ‘struct'» on the the first line in the function allocate() below. I cant figure out why.
I should say that I’ve been tasked to make this code work with the structure / function headers provided.
Any help is much appreciated!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <time.h>
struct student{
int id;
int score;
};
struct student* allocate(){
/*Allocate memory for ten students*/
struct student *stud = malloc(10 * sizeof struct *student);
assert (stud !=0);
return stud;
}
void generate(struct student *students){
/*Generate random ID and scores for ten students, ID being between 1 and 10, scores between 0 and 100*/
srand(time(NULL));
// Generate random ID's
int i;
for(i=0; i<10; i++){
students[i].id = rand()*10+1;
}
//Generate random scores
for(i=0; i<10; i++){
students[i].score = rand()*10+1;
}
}
void output(struct student* students){
//Output information about the ten students in the format:
int i;
for(i=0; i<10; i++){
printf("ID-%d Score-%dn", students[i].id, students[i].score);
}
}
void summary(struct student* students){
/*Compute and print the minimum, maximum and average scores of the ten students*/
int min = 100;
int max = 0;
int avg = 0;
int i;
for(i=0; i<10; i++){
if(students[i].score < min){
min = students[i].score;
}
if(students[i].score > max){
max = students[i].score;
}
avg = avg + students[i].score;
}
avg = avg/10;
printf("Minimum score is %d, maximum score is %d, and average is %d.", min, max, avg);
}
void deallocate(struct student* stud){
/*Deallocate memory from stud*/
free (stud);
}
int main(){
struct student *stud = NULL;
/*call allocate*/
stud = allocate();
/*call generate*/
generate(stud);
/*call output*/
output(stud);
/*call summary*/
summary(stud);
/*call deallocate*/
deallocate(stud);
return 0;
}
asked Apr 16, 2013 at 3:38
You may want to write
sizeof(struct student)
instead of
sizeof struct *student
answered Apr 16, 2013 at 3:41
KrishnabhadraKrishnabhadra
34.1k30 gold badges117 silver badges165 bronze badges
2
Your problem is in sizeof struct *student. When using the sizeof operator on a typename, you need to parenthesize the typename. In addition, as Jonathan Leffler identified in the comments to this answer, the placement of * in struct *student is erroneous, and the use of struct student * would be incorrect in the context of this code. Perhaps you meant: sizeof (struct student).
Alternatively, you could use sizeof on an expression, and you won’t need the parenthesis. This would be preferable, because if you choose to change the type of stud then you won’t need to replace an extra typename when you do so: struct student *stud = malloc(10 * sizeof *stud);
answered Apr 16, 2013 at 3:43
2
void insert(int x, struct Node **pL)
{
So far this tells you you get a pointer to a pointer, a clear sign your function should modify *pL if necessary.
if(*pL == NULL){
*pL = malloc(sizeOf(struct Node *pL)); // error here
and you try here, but the syntax is wrong. First it’s sizeof, not sizeOf. C is case sensitive. Then the sizeof operator takes either a type or an expression to determine its storage size. So you can either write sizeof(struct Node) or sizeof(**pL). Note the double asterisk here, what you want is the storage size of a struct Node and with only one asterisk, your expression would be of type struct Node * (a pointer to a struct Node).
*pL->value = x; // error #2
This is just wrong because -> has higher precedence than *, so it means *(pL->value) = x;. Not what you want, you want (*pL)->value = x;.
*pL->next = NULL;
}else if(*pL != NULL){
This line doesn’t make much sense (although not exactly an error). *pL can either be NULL or not be NULL. A plain else will do here.
insert(x, &((*pL)->next));
}
}
I really wonder why you get the parenthesis correct in this last line and still don’t see the error some lines above yourself? Just adding here: being precise and conscientious is crucial in programming (and even more so in a language like C).
All in all, the code should probably look like this:
void insert(int x, struct Node **pL)
{
if(*pL == NULL) {
*pL = malloc(sizeof(struct Node));
(*pL)->value = x;
(*pL)->next = NULL;
} else {
insert(x, &((*pL)->next));
}
}
12-30-2009
#1
Registered User
expected primary-expression before «struct»
Hi boys, I wrote this nice program in c++ a good deal was copied dev-c++ latest version keeps giving this error at the compilation : expected primary-expression before «struct»
I write here just the first part of the code till the mistake, you will find it at the line before the last.
I need it for a working interview and I am a bit nervous about it.
Thanks in advance-
DoraCode:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> //#include "sort_words.h" struct word_item { char * word; struct word_item * next; }; struct word_list { int length; struct word_item * first_word; struct word_list * next; }; struct word_list * first_word_list = NULL; char * read_word(FILE * fin){ char c; int i; char * buffer = (char *)malloc(sizeof(char)); buffer[0] = ''; for (i=0; (c = fgetc(fin))!=EOF; i++) { if (isspace(c) || ispunct(c)) break; buffer[i] = c; buffer = (char *)realloc(buffer, sizeof(char)*(i+1)); buffer[i+1] = ''; } if (c == EOF) return NULL; return buffer; } /* void init_word_list() { first_word_list = NULL; } */ struct word_list * init_word_list_item(int length, struct word_list * next, struct word_item * item) { struct word_list * word_list_item; word_list_item = (struct word_list *) malloc(sizeof(struct word_list)); if (word_list_item == NULL) { printf("cannot allocate enough memoryn"); exit(-1); } word_list_item->length = length; word_list_item->next = next; word_list_item->first_word = item; return word_list_item; } /*void append_word_item(struct word_list * current, struct word_list * new) { new->next = current->next; current->next = new; }*/ struct word_list * get_word_list_item(int length) { struct word_list * cwl = NULL; struct word_list * new = NULL; // Here the error is given struct word_list * previous = NULL;
I’m doing a lab on Linked Lists in C, and I’m getting an error that I can’t seem to shake. The lab is due in 2 hours so any help would be amazing!
This is what I have for code:
void insert(int x, struct Node **pL)
{
if(*pL == NULL){
*pL = malloc(sizeOf(struct Node *pL)); // error here
*pL->value = x; // error #2
*pL->next = NULL;
}else if(*pL != NULL){
insert(x, &((*pL)->next));
}
}
Any thoughts?!!
That covered that error, but now I’m getting an error that says, «error: request for member ‘value’ in something not a structure or union.
FINISHED! THANK YOU FOR ALL OF THE HELP!
void insert(int x, struct Node **pL)
{
So far this tells you you get a pointer to a pointer, a clear sign your function should modify *pL if necessary.
if(*pL == NULL){
*pL = malloc(sizeOf(struct Node *pL)); // error here
and you try here, but the syntax is wrong. First it’s sizeof, not sizeOf. C is case sensitive. Then the sizeof operator takes either a type or an expression to determine its storage size. So you can either write sizeof(struct Node) or sizeof(**pL). Note the double asterisk here, what you want is the storage size of a struct Node and with only one asterisk, your expression would be of type struct Node * (a pointer to a struct Node).
*pL->value = x; // error #2
This is just wrong because -> has higher precedence than *, so it means *(pL->value) = x;. Not what you want, you want (*pL)->value = x;.
*pL->next = NULL;
}else if(*pL != NULL){
This line doesn’t make much sense (although not exactly an error). *pL can either be NULL or not be NULL. A plain else will do here.
insert(x, &((*pL)->next));
}
}
I really wonder why you get the parenthesis correct in this last line and still don’t see the error some lines above yourself? Just adding here: being precise and conscientious is crucial in programming (and even more so in a language like C).
All in all, the code should probably look like this:
void insert(int x, struct Node **pL)
{
if(*pL == NULL) {
*pL = malloc(sizeof(struct Node));
(*pL)->value = x;
(*pL)->next = NULL;
} else {
insert(x, &((*pL)->next));
}
}
- Forum
- Beginners
- help me about error» expected primary-ex
help me about error» expected primary-expression before «struct» «
When I write the following function gives the following error What is the problem?
|
|
and errors:
|
|
1) line 13. You do not need to write struct tchr . Just tchr will be fine.
2) Using uninitalizated pointers tn tm and tf (illegal and can lead to crash)
3) Lines 31-34 I am at loss waht happens here.
Looks like you are creating 4 variables of the same name (inllegal) which are variable length arrays (illegal) and using member selection in time of initialization (illegal)
If you want to modify variable declared in main(), you should pass it to your function.
Also there is no sense to pass characters by pointer. Use palin old chars here.
This happens in lines 31-34 tm and tf, tد, Tcode that were taken in each part of the Main() Plan struct stores.
Unfortunately I am not native English speakers. I do not know if you’ve noticed my posts?
|
|
Fixed function. However you have so many problems in other parts that it is probably going to crash right away.
Last edited on
Thank you
there are a couple of issues that spring to mind.
Firstly, t[] is declared locally to main() but you are trying to access it from insertchr()
you are using alot of character pointers, these usually cause problems for beginners, replace them with character arrays to simplify your code.
you can improve this code greatly by using std::string
|
|
Topic archived. No new replies allowed.
Hello again,
I try compilation openlierox 0.58_rc3 and :
-- The C compiler identification is GNU 4.8.2
-- The CXX compiler identification is GNU 4.8.2
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
SYSTEM_DATA_DIR = /usr/share/games
DEBUG = ON
DEDICATED_ONLY = OFF
G15 = OFF
X11 = ON
HAWKNL_BUILTIN = ON
LIBZIP_BUILTIN = OFF
STLPORT = OFF
GCOREDUMPER = OFF
BREAKPAD = Off
CMAKE_C_COMPILER = /usr/bin/cc
CMAKE_C_FLAGS = -O2 -fPIC
CMAKE_CXX_COMPILER = /usr/bin/c++
CMAKE_CXX_FLAGS = -O2 -fPIC
OLX_VERSION = 0.58_rc3
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/SBo/openlierox-0.58_rc3/build
Scanning dependencies of target openlierox
[ 0%] Building CXX object CMakeFiles/openlierox.dir/src/main.o
In file included from /tmp/SBo/openlierox-0.58_rc3/./include/FileDownload.h:30:0,
from /tmp/SBo/openlierox-0.58_rc3/./include/CClient.h:31,
from /tmp/SBo/openlierox-0.58_rc3/src/main.cpp:20:
/tmp/SBo/openlierox-0.58_rc3/./include/HTTP.h:24:24: fatal error: curl/types.h: No such file or directory
#include <curl/types.h>
^
compilation terminated.
make[2]: *** [CMakeFiles/openlierox.dir/src/main.o] Error 1
make[1]: *** [CMakeFiles/openlierox.dir/all] Error 2
make: *** [all] Error 2
This error fixed after change the curl header curl/types.h —> curl/typecheck-gcc.h in HTTP.h file.
but I also the same error in file HTTP.cpp not corrected in the same way.
compilation crash at 68% :
curl_easy_setopt(curl, CURLOPT_HTTPPOST, curlForm);
^
/tmp/SBo/openlierox-0.58_rc3/src/common/HTTP.cpp:277:2: error: expected primary-expression before ‘__typeof__’
curl_easy_setopt(curl, CURLOPT_HTTPPOST, curlForm);
^
/tmp/SBo/openlierox-0.58_rc3/src/common/HTTP.cpp:277:2: error: expected primary-expression before ‘const’
curl_easy_setopt(curl, CURLOPT_HTTPPOST, curlForm);
^
/tmp/SBo/openlierox-0.58_rc3/src/common/HTTP.cpp:277:2: error: expected primary-expression before ‘__typeof__’
curl_easy_setopt(curl, CURLOPT_HTTPPOST, curlForm);
^
/tmp/SBo/openlierox-0.58_rc3/src/common/HTTP.cpp:277:2: error: expected primary-expression before ‘char’
...
make[2]: *** [CMakeFiles/openlierox.dir/src/common/HTTP.o] Error 1
make[1]: *** [CMakeFiles/openlierox.dir/all] Error 2
make: *** [all] Error 2
Добрый вечер, форумчане!
Продолжаю «практиковать» скилл в Си и наконец добралась до структур. Всё бы ничего, но в таком куске кода выдает множество однотипных ошибок. Не подскажите в чем именно дело?
| C | ||
|
Смысл всего действа: функция должна возвращать заполненную пользователем структуру.
In function ‘input_car’:
Line 12: warning: empty declaration with storage class specifier does not redeclare tag
Line 14: error: expected expression before ‘auto’
Line 16: error: expected expression before ‘auto’
Line 18: error: expected expression before ‘auto’
Line 20: error: expected expression before ‘auto’
Line 22: error: expected expression before ‘auto’
Line 24: error: expected expression before ‘auto’
Line 26: error: expected expression before ‘auto’
Line 27: error: expected expression before ‘auto’
Дальше по коду еще больше ошибок, но суть их такая же
Добавлено через 24 минуты
До меня дошло, что «auto» — зарезервированное слово, а не просто перевод слова «машина». Всем спасибо, все свободны
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
13 Years Ago
Hi boys, I am working for a job interview and I was writing a nice piece of cod in c++, partially copied and pasted.
This is supposed to work but now i am obliged to use dev-c++ last version for windows, usually I just use gcc on linux and I at the compilation I receive: expected primary-expresion before «struct».
I write the first part of the code till one line after the error, I really need to have this running, I suspect it is a problem with the compiler, please help.
Thanks in advance,
Dora
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//#include "sort_words.h"
struct word_item {
char * word;
struct word_item * next;
};
struct word_list {
int length;
struct word_item * first_word;
struct word_list * next;
};
struct word_list * first_word_list = NULL;
char * read_word(FILE * fin){
char c;
int i;
char * buffer = (char *)malloc(sizeof(char));
buffer[0] = '';
for (i=0; (c = fgetc(fin))!=EOF; i++) {
if (isspace(c) || ispunct(c))
break;
buffer[i] = c;
buffer = (char *)realloc(buffer, sizeof(char)*(i+1));
buffer[i+1] = '';
}
if (c == EOF)
return NULL;
return buffer;
}
/*
void init_word_list() {
first_word_list = NULL;
}
*/
struct word_list *
init_word_list_item(int length, struct word_list * next, struct word_item * item) {
struct word_list * word_list_item;
word_list_item = (struct word_list *) malloc(sizeof(struct word_list));
if (word_list_item == NULL) {
printf("cannot allocate enough memoryn");
exit(-1);
}
word_list_item->length = length;
word_list_item->next = next;
word_list_item->first_word = item;
return word_list_item;
}
/*void append_word_item(struct word_list * current, struct word_list * new) {
new->next = current->next;
current->next = new;
}*/
struct word_list * get_word_list_item(int length) {
struct word_list * cwl = NULL;
struct word_list * new = NULL; // Here the error is given
struct word_list * previous = NULL;
Recommended Answers
You probably compiled it as C++, where new is a reserved word.
Jump to Post
All 4 Replies
nezachem
616
Practically a Posting Shark
13 Years Ago
You probably compiled it as C++, where new is a reserved word.
Agni
370
Practically a Master Poster
Featured Poster
13 Years Ago
It doesn’t look like C++ code at all. And the moderators might prove that in sometime by moving it to the C forum !!
13 Years Ago
Before I say something, what do you think this statement is doing :
struct word_list * new = NULL;
13 Years Ago
It doesn’t look like C++ code at all. And the moderators might prove that in sometime by moving it to the C forum !!
you are right and this means I am terribly wrong, after what u wrote i figured out I was compiling with the option c++ checked on instead of ANSI c.
Sorry for wasting your time, it may consoulate you I wasted much more in a difficult situation.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.


