Home > Net >  Error: expected identifier or ‘(’ before ‘->’ token in C
Error: expected identifier or ‘(’ before ‘->’ token in C

Time:10-04

I have a struct, located in my header file, and I want to set its members to values I have in my main() function, those being "size" and "cap". I get the following: error: expected identifier or ‘(’ before ‘->’ token struct Array->size = size; I also get the same error for the line with "cap."

I've provided my header file, where the struct is found, and my function definitions file.

Header File:

#include <stdio.h>

struct Array {
  unsigned int size;
  unsigned int cap;
  int data;
};

struct Array *newArray(unsigned int size, unsigned int cap); //Prototype

Function Definition File:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

struct Array *newArray(unsigned int size, unsigned int cap) {

  struct Array->size = size;
  struct Array->cap = cap;

}

I have intentionally not included my header file in my function definitions file because I include it in my main file. Having header.h included twice gives me more errors/warnings.

Could anyone please help? Thanks

CodePudding user response:

You are trying assign something to a type which does work.

struct Array *newArray(unsigned int size, unsigned int cap) {

   struct Array->size = size;
   struct Array->cap = cap;

}

Here is how to fix your code:

struct Array *newArray(unsigned int size, unsigned int cap) {
   struct Array *arr = malloc(sizeof(struct Array));
   if(!arr)
       return NULL;

   arr->size = size;
   arr->cap = cap;
   
   return arr;
}

CodePudding user response:

You need to create a new instance of the Array struct, initialize its fields, and return pointer to it in the newArray function.

  • Related