Casting a pointer in C - c

I created a function which returns a pointer to an object of a self-made structure. Then, I declared another pointer which I set equal to a pointer returned by the the aforementioned function. I get the error "Assignment makes pointer from integer without a cast" - but I do not understand why I should be casting... because all of these pointers were declared to be of the same type.
In disk.h I defined the following:
struct generic_attribute{
char *name;
int current_value;
int previous_value;
//int time_series[500];
};
In disk.c, I made a constructor for generic_attribute like so:
#include "disk.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
struct generic_attribute* construct_generic_attribute(char* name, int current_value){
struct generic_attribute *ga_ptr;
//ga_ptr = (struct generic_attribute*) malloc (sizeof(struct generic_attribute));
ga_ptr = malloc (sizeof (struct generic_attribute));
ga_ptr -> name = name;
ga_ptr -> current_value = current_value;
ga_ptr -> previous_value = 0;
return ga_ptr;
}
In disk_test.c I want to test this constructor:
#include "disk.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
void test_generic_attribute_constructor(char* name, int current_value){
struct generic_attribute* ga_ptr;
ga_ptr = construct_generic_attribute(name, current_value);
printf("%i\n", construct_generic_attribute(name, current_value));
}
int main() {
test_generic_attribute_constructor("test", 2000);
}
I get the error on this line:
ga_ptr = construct_generic_attribute(name, current_value);
I do not understand why. ga_pointer was declared as a pointer to type struct generic_attribute. So was the return of function construct_generic_attribute. I am new to C, so I might be misunderstanding how all of this works.

You did not declare construct_generic_attribute() in disk.h, so upon seeing the function call the compiler assumes it has the default signature -- that is, int construct_generic_attribute();.
Thanks for questioning this instead of blindly adding the cast (which could have seemed to work !)

You are missing the function declaration in your header file, disk.h.
add the declaration:
struct generic_attribute* construct_generic_attribute(char* ,int);
and the compiler will know the return type of your function is a pointer.

add following line in disk_test.c :
struct generic_attribute* construct_generic_attribute(char* ,int);

Related

C Declare array of struct/pointer to array of structs

I have an example tutorial with 2 files, "functions.c" and "functions.h" which contain the prototypes and the body of the functions.
In the example there isn't the main that containing the declaration of the array of struct/pointer to array of structs and the calls to the functions.
functions.c:
#include "functions.h"
const char *getTeamA(const sTest *p)
{
return p->teamA;
}
void setTeamA(sTest *p, char *s)
{
strcpy(p->teamA, s);
}
int getNum(const sTest *p)
{
return p->num;
}
void setNum(sTest *p, int i)
{
p->num = i;
}
functions.h:
#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CHAR 20
#define SIZE 5
typedef struct {
char teamA[MAX_CHAR];
int num;
// ...
} sTest;
const char *getTeamA(const sTest *p);
void setTeamA(sTest *p, char *s);
int getNum(const sTest *p);
void setNum(sTest *p, int i);
#endif /* FUNCTIONS_H_ */
So my question is
How can i declare the struct according to the code written above?
So for example:
int main()
{
sTest data[SIZE]; //size isn't important
sTest *dataPtr = data;
setTeamA(dataPtr[0].teamA, "name1");
// ...
printf("%d", getNum(dataPtr[1].num)); // just an example. i know that it isn't initialized
// ...
return 0;
}
Is this the correct way? Or is there a better way to declare variables and pass them to the functions?
The important thing is that i have to stick to the code written in functions.c and functions.h, so the functions cannot directly modify the struct data, you need to use pointers (because there are member selection operator "->" in functions.c).
You don't need to have dataPtr. You can do the exact same thing by doing data[i], since you declared data as an array of sTests, and so data points to the first element in the array.
Let's deconstruct what you're doing when you're calling setTeamA(dataPtr[0].teamA, "name1"). You're trying to set the first sTest struct in the data array to have "name1" as the teamA field. Notice that the prototype for setTeamA() actually takes in a sTest *p. In your example, you're passing in the teamA field. So what you really want to call is setTeamA(&dataPtr[0], "name1"). This translates to the pointer pointing to the data at dataPtr[0].
While this works, as I said before, the dataPtr is unecessary. So this is equivalent to:
setTeamA(&data[0], "name1").
Also worth noting, you can simply write:
setTeamA(data, "name1")
since data is already a pointer to the first element in the array.
Use
setTeamA(&data[0], "name1")
It indexes to index 0 and then takes the reference (which is a pointer) of the result therefore making the type an sTest* then the setTeamA function will do it's job setting the teamA field.
That dataPtr variable is useless here.

Undeclared variable c in structure pointer function

I am still learning C and I am doing an exercise where I have to program a car database. In the main function I declared an array of 100 pointers to 'carinfo_t' structures. In the function '*createcarinfo' a new carinfo_t instance should be created. But I get the problem that the 'brandOfCar' variable is undeclared. I do not really understand why I am getting this message because the compiler should know that this variable is part of the structure, right? The structure is declared as a datatype in the program and a pointer to the struct is initialized in the beginning of this function.
I am sorry if this question has already been asked somewhere. Any help is very much appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <limits.h>
struct carinfo_t
{
char *brandOfCar;
char *modelOfCar;
int yearCarWasBuilt;
float valueOfCar;
};
struct carinfo_t *createCarinfo(char *brand, char *model, int year, float
value)
{
struct carinfo_t *newCarInfo=(struct carinfo_t*) malloc(sizeof(struct
carinfo_t));
newCarInfo->brandOfCar=(char*)malloc(sizeof(char)*
(strlen(brandOfCar)+1));
//Message: error: 'brandOfCar' undeclared (first use in this function)
//function not finished
}
int main()
{
struct carinfo_t *carbase[100]={};
return 0;
}
This is because you called the variable passed into your constructor function brand, not brandOfCar. Similarly, you called model variable model, not modelOfCar. That's why strlen does not compile.
It's a good idea to name variables identically to the fields of the structure for consistency, and add const where it is appropriate:
struct carinfo_t *createCarinfo(
const char *brandOfCar
, const char *modelOfCar
, int yearCarWasBuilt
, float valueOfCar) {
struct carinfo_t *newCarInfo=malloc(sizeof(struct carinfo_t));
newCarInfo->brandOfCar=malloc(strlen(brandOfCar)+1);
...
}
Also note that in C you do not cast malloc, and do not multiply by sizeof(char), which standard requires to be 1 on all platforms.

Allocating memory for structure types in C

Im having an issue in my program where I define a structure type but not a structure variable in a header as such.
typedef struct
{
int a;
int b;
int c;
Token d;
} Foo;
I then want to use this struct foo later on in a .c file that does infix to postfix
#include "header"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
int infix2postfix(char *infix, Arr arr)
{
struct Foo foo;
char szToken[MAX_TOKEN];
Stack stack = newStack();
infix = getToken(infix, szToken, MAX_TOKEN); //provides next token to be scanned by function.
... //push pop using switch case didn't post code for simplicity.
case...
push(stack, *foo.a);
...
case...
pop(stack);
...
goOut(arr, *foo.d); //goOut(function that populates and "arr" Array from printing.
}
So when I compile here I get
error: storage size of ‘foo’ isn’t known struct Foo foo;
I have tried struct Foo *foo = malloc(sizeof foo); to allocate memory but it messes up my push(stack, *foo.a); and goOut(arr, *foo.d); How do I go about fixing this? Do I have to allocate memory in the infix2postfix function first then declare a structure variable?
You defined a type Foo which is a tagless struct type. You could have a separate struct Foo { int anonymous; char name[MAX_NAME]; }; which is wholly unrelated to the type Foo. (It would be very confusing for humans, but the compiler would have no problem.)
In your function, you should write:
int infix2postfix(char *infix, Arr arr)
{
Foo foo;
you have already defined Foo as a typedef struct, so you do not use struct Foo again to declare foo, just use
Foo foo; to declare not struct Foo foo;

New to C... struct can't find a variable I identified

I'm new to this whole C thing, but I keep getting this error with my code
UArray2.c:19:error: request for member ‘i’ in something not a structure or union
It's obviously the uarray.i in my main function, but I don't get why it isn't seeing it.
This is my .h file. Not too interesting...
//UArray2.h
#include <stdlib.h>
#include <stdio.h>
#ifndef UARRAY2_INCLUDED
#define UARRAY2_INCLUDED
#define T UArray2_T
typedef struct T *T;
#undef T
//#undef UARRAY2_INCLUDED //undef?
#endif
This is my .c file. Pretty simple stuff.
//UArray.c
#include <stdlib.h>
#include <stdio.h>
#include "UArray2.h"
#define T UArray2_T
struct T{
int i;
};
int main()
{
UArray2_T uarray;
uarray.i=0;
return 0;
}
#undef T
So, does anyone have any idea as to why I'm getting this compile error? It's likely something stupid that I did.
In the header file you have
typedef struct T *T;
This means that when you declare the variable uarray you are actually declaring a pointer. So you should initialize the i member as
uarray->i = 0;
This will however most likely crash, as the pointer is uninitialized and can point to any location in memory. Either allocate memory for the pointer
UArray2_T uarray = malloc(sizeof(*uarray));
Or make it point to another structure
struct UArray2_T real_uarray;
UArray2_T uarray = &real_uarray;
I think there is a problem with the initialization as you are using the pointer in the header file.
typedef struct T *T;
You are actually pointing to the memory location by declaring uarray.
Try to rectify this error.

Having trouble accessing struct elements returned by a function - dereferencing pointer to incomplete type

I am new to C.This are the files and codes that I am working on. I am trying to call a function (refineMatch) implemented in a separate file from the main function. function refineMatch returns a struct. I am having problems in compiling the code which is related to accessing elements in the returned struct. The compile error occurs in main.c file. Code below shows where the error happens.
refine.h
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
struct matchingpair{
CvPoint p1, p2;
};
struct matchingpair_array{
struct matchingpair* elements;
int length;
};
struct matchingpair_array *refineMatch(struct matchingpair* pairs,int pointcount, int bestpair);
refine.c
#include "refine.h"
#include "utils.h"
#include <stdlib.h>
struct matchingpair_array *refineMatch(struct matchingpair* pairs,int pointcount, int bestpoint){
struct matchingpair_array refinedPairs;
refinedPairs.elements=malloc(incount*sizeof(struct matchingpair));
int *in=malloc(pointcount*sizeof(int)), i=0,incount=8;
// several statements - including filling in[] with data
for(i=0;i<incount;i++){
refinedPairs.elements[i]=pairs[in[i]];
fprintf(stderr,"%d\n",in[i]);
}
refinedPairs.length=incount;
free(in);
// several other free() operations non include refinedPairs or elements
return &refinedPairs;
}
main.c
#include "refine.h"
#include <stdio.h>
int main( int argc, char** argv ){
struct matchingpair* pairs;
int matchcount=0,bestpair;
pairs=(struct matchingpair*)malloc(pairArrSize*sizeof(struct matchingpair));
//values are assigned to pairs, matchcount and bestpair
struct matcingpair_array* result=(struct matcingpair_array*)refineMatch(pairs,matchcount,bestpair); /*(casting removed this warining)
warning: initialization from incompatible pointer type*/
fprintf(stderr,"%d \n",result->length); //error: dereferencing pointer to incomplete type
//some other code
}
Please explain me what I am doing wrong here. I am using gcc.
Thank you.
refineMatch() does not return a struct. It returns a pointer to a struct matchingpair_array.
and matcingpair_array is not the same as mathcingpair_array: it is missing an h

Resources