I am trying to use struct called BankAccount it takes char array of name 50 letters long , int ID, and double balance. I am trying to use malloc() to put it to pointer but i get this
error : void can not be assigned to an entity of type BankAccount.
typedef struct
{
char name[50];
int ID;
double balance;
} BankAccount;
FILE *fp;
BankAccount *accounts = 0;
int accountSize = 0;
// I init like this in main function
accounts = malloc(accountSize * sizeof(*accounts));
void ReadAccountData(BankAccount *accounts, FILE *fp, int arraySize)
{
int i = 0;
while (!feof && i < arraySize) {
fread(&accounts, sizeof(accounts), i, fp);
i++;
}
}
If you are using C language, you need to use C compiler for your code. The compiler you are using now looks like C++ compiler, which requires casting void * to destined type. In C you shouldn't do this, as pointed out by #Olaf (Why you can't cast void * in C).
How to change compilator? It depends on IDE and operating system, that you are using, this needs to be specified before I can give any more details.
If you want to use C++ you have few options:
Use malloc, but cast return value:
accounts = static_cast<BankAccount *>(
malloc(accountSize * sizeof(BankAccount)));
Use dynamic allocation dedicated for C++ and treat BankAccount as C++ structure(you can add constructors, destructors, methods etc.):
accounts = new BankAccount[accountSize];
Should be like this:
accounts = (BankAccount *)malloc(accountSize * sizeof(BankAccount));
Related
Does C have anything similar to C++ where one can place structs in an unsigned char buffer as is done in C++ as shown in the standard sec. 6.7.2
template<typename ...T>
struct AlignedUnion {
alignas(T...) unsigned char data[max(sizeof(T)...)];
};
int f() {
AlignedUnion<int, char> au;
int *p = new (au.data) int; // OK, au.data provides storage
char *c = new (au.data) char(); // OK, ends lifetime of *p
char *d = new (au.data + 1) char();
return *c + *d; // OK
}
In C I can certainly memcpy a struct of things(or int as shown above) into an unsigned char buffer, but then using a pointer to this struct one runs into strict aliasing violations; the buffer has different declared type.
So suppose one would want to replicate the second line in f the C++ above in C. One would do something like this
#include<string.h>
#include<stdio.h>
struct Buffer {
unsigned char data[sizeof(int)];
};
int main()
{
struct Buffer b;
int n = 5;
int* p = memcpy(&b.data,&n,sizeof(int));
printf("%d",*p); // aliasing violation here as unsigned char is accessed as int
return 0;
}
Unions are often suggested i.e. union Buffer {int i;unsigned char b[sizeof(int)]}; but this is not quite as nice if the aim of the buffer is to act as storage (i.e. placing different sized types in there, by advancing a pointer into the buffer to the free part + potenially some more for proper alignment).
Have you tried using a union?
#include <string.h>
#include <stdio.h>
union Buffer {
int int_;
double double_;
long double long_double_;
unsigned char data[1];
};
int main() {
union Buffer b;
int n = 5;
int *p = memcpy(&b.data, &n, sizeof(int));
printf("%d", *p); // aliasing violation here as unsigned char is accessed as int
return 0;
}
The Buffer aligns data member according the type with the greatest alignment requirement.
Yes, because of strict aliasing rule it is just not possible. As it is not possible to write a standard compliant malloc().
Your buffer is not aligned - alignas(int) from stdalign.h needs to be added.
If you want to protect against compiler optimizations, either:
just cast the pointer and access it and compile with -fno-strict-aliasing, or use volatile
or move the accessor to the buffer to another file that is compiled without LTO so that compiler just is not able to optimize it.
// mybuffer.c
#include <stdalign.h>
alignas(int) unsigned char buffer[sizeof(int)];
void *getbuffer() { return buffer; }
// main.c
#include <string.h>
#include <stdio.h>
#include "mybuffer.h"
int main() {
void *data = getbuffer();
// int *p = new (au.data) int; // OK, au.data provides storage
int *p = data;
// char *c = new (au.data) char(); // OK, ends lifetime of *p
char *c = data;
*c = 0;
// char *d = new (au.data + 1) char();
char *d = (char*)data + 1;
*d = 0;
return *c + *d;
}
The way the definition of Effective Type in 6.5p6 is written, it's unclear what it's supposed to mean in all corner cases--likely because there was never a consensus among Committee Members as to how all corner cases should be handled. Defect reports often add more confusion than clarity, since they use terms like the "active member" of a union when neither the Standard nor the defect reports specify what actions would set or change it.
If one wants to use an object of static or automatic duration as though it were a buffer without a declared type, a safe way of doing that should be to do something like the following:
void volatile *volatile dummy_vp;
void test(void)
{
union {
char dat[1000];
unsigned long force_alignment;
} buffer;
void *volatile launder = buffer.dat;
dummy_vp = &launder;
void *storage_blob = launder;
...
}
Unless an implementation goes out of its way to test whether the read of
launder happened to yield an address matching buffer.dat, it would have no way of knowing whether the object at that address had a declared type. Nothing in the Standard would forbid an implementation from behaving nonsensically if the address happened to match that of buffer.dat, but situations where performance improvements would justify the cost of the check aren't likely to be common enough for compilers to attempt such "optimization".
I'm trying to refactor a utility that is currently a stand-alone C program, such that I can make a reusable library. It includes a sorting step of an array, according to the corresponding value within a global array.
// Global lookup table
double *rating;
// Comparator using lookup
int comp_by_rating(const void *a, const void *b) {
int * x = (int *) a;
int * y = (int *) b;
if (rating[*x] > rating[*y])
return 1;
else if (rating[*x] < rating[*y])
return -1;
else
return 0;
}
int main() {
int* myarray;
// ...
// initialize values of local myarray and global rating
// ...
qsort(myarray, length_myarray, sizeof(int), comp_by_rating);
// ...
return 0;
}
Is there a way for me to avoid having the rating lookup table global? I'm traditionally a C++ person so my first thought was a functor, but I have to stay in C and so I guess I'm functor-less. I also can't replace int *myarray with an array of structs holding the rating for each item, since other code requires the array in its current form. Do I have any other options?
I also can't replace int *myarray with an array of structs holding the rating for each item, since other code requires the array in its current form.
You can make a temporary replacement for sorting, call qsort, and harvest the results back into the original array:
struct rated_int {
int n;
double r;
};
struct rated_int *tmp = malloc(length_myarray * sizeof(struct rated_int));
for (int i = 0 ; i != length_myarray ; i++) {
tmp[i].n = myarray[i];
tmp[i].r = ratings[myarray[i]];
}
qsort(tmp, length_myarray, sizeof(struct rated_int), comp_struct);
for (int i = 0 ; i != length_myarray ; i++) {
myarray[i] = tmp[i].n;
}
free(tmp);
This way the rest of the code would see myarray as an array of integers.
That's how you roll in C. If you are worried about thread-safety, consider making the variable thread-local, so multiple threads have different copies of it:
static _Thread_local double *rating;
This is not supported by old compilers though, instead you need some sort of portability kludge. If you don't like this either, you can't really get around writing your own sorting routine that allows an extra parameter.
gcc provides nested functions as an extension to solve this problem, but they have other problems, namely, they require an executable stack which reduces the resilience of your program against bugs.
No, the array rating does not have to be global: You can use static here:
int comp_by_rating(const void *a, const void *b) {
static double *rating = { .. init here .. };
Alternate way to initialize it if members are non-constant:
int comp_by_rating(const void *a, const void *b) {
static double *rating = NULL;
if (!rating) {
// Initialize rating here
}
}
This question already has answers here:
Get list of C structure members
(6 answers)
Closed 7 years ago.
I have two variables called x and y in a structure called mystruct, when I have the program I want to be able to display the variable names with its value like this.
mystruct.x --> 3, mystruct.y --> 5
Is there a way to do this without just putting mystruct.x in the printf like a string in c?
you can't extract the name of the struct in a smart and clean way.
the possibility to call the type of a variable or a struct is called "Reflection" - the application ability to reflect upon itself (either in compile or runtime) and extract data like the type, typename, inner variables etc.
this is not supported at all in C. thinking about it , C doesn't care- a struct is basically a row in the memory (like any other variable in C, actually).
you can however , make a not-so-smart implementation that stores the typename equivilant to the memory address :
struct memory_address_to_type_name{
char type_name [20],
void* memory_address
} name_memory_address_map[50];
char* get_name (void* variable){
int i;
for (i=0;i<50;i++){
if (variable == name_memory_address_map[i].memory_address)){
return name_memory_address_map[i].type_name;
}
}
return "not found";
}
int push_name (void* variable , char* type_name){
int i;
for (i=0;i<50;i++){
if (strcmp(name_memory_address_map[i].type_name,"") == 0){
name_memory_address_map[i].memory_address = variable;
strcpy(name_memory_address_map[i].type_name,type_name);
}
return 1;
}
return 0;
}
}
int main (void){
myStruct x;
push_name (&x,"myStruct");
//other code
printf("%s --> %d",get_name(x),x.my_member);
}
of course , this is not a complete example. you do want to use a linked list instead of a ad-hoc bounded array , do much more protecting against overflows and out of arrays errors , etc. this is only the idea.
as a side note (and I might get downvoted for this), as a C++ developer, your problem could be much more easily solved in C++ by using a typeid(x).name() (if the implementation does return normal string , like VC++ implementation) , or reproduce the solution above with std::map and std::string . but this is a side note only.
do you mean something like this: http://ideone.com/3UeJHv:
#include <stdio.h>
#define PRINT_INT(X) printf(#X"-->%d\n",X)
#define PRINT_STUDENT(X) printf(#X".x-->%d " #X".y-->%d\n" ,X.x ,X.y)
struct student
{
int x;
int y;
};
int main()
{
int c = 10;
PRINT_INT(c);
struct student stud1 = {200 , 300};
struct student stud2 = {400 , 500};
PRINT_STUDENT(stud1);
PRINT_STUDENT(stud2);
return 0;
}
output:
c-->10 stud1.x-->200 stud1.y-->300 stud2.x-->400 stud2.y-->500
I came across this simple program somewhere
#include<stdio.h>
#include<stdlib.h>
char buffer[2];
struct globals {
int value;
char type;
long tup;
};
#define G (*(struct globals*)&buffer)
int main ()
{
G.value = 233;
G.type = '*';
G.tup = 1234123;
printf("\nValue = %d\n",G.value);
printf("\ntype = %c\n",G.type);
printf("\ntup = %ld\n",G.tup);
return 0;
}
It's compiling (using gcc) and executing well and I get the following output:
Value = 233
type = *
tup = 1234123
I am not sure how the #define G statement is working.
How G is defined as an object of type struct globals ?
First, this code has undefined behavior, because it re-interprets a two-byte array as a much larger struct. Therefore, it is writing past the end of the allocated space. You could make your program valid by using the size of the struct to declare the buffer array, like this:
struct globals {
int value;
char type;
long tup;
};
char buffer[sizeof(struct globals)];
The #define is working in its usual way - by providing textual substitutions of the token G, as if you ran a search-and-replace in your favorite text editor. Preprocessor, the first stage of the C compiler, finds every entry G, and replaces it with (*(struct globals*)&buffer).
Once the preprocessor is done, the compiler sees this code:
int main ()
{
(*(struct globals*)&buffer).value = 233;
(*(struct globals*)&buffer).type = '*';
(*(struct globals*)&buffer).tup = 1234123;
printf("\nValue = %d\n",(*(struct globals*)&buffer).value);
printf("\ntype = %c\n",(*(struct globals*)&buffer).type);
printf("\ntup = %ld\n",(*(struct globals*)&buffer).tup);
return 0;
}
The macro simply casts the address of the 2-character buffer buf into a pointer to the appropriate structure type, then de-references that to produce a struct-typed lvalue. That's why the dot (.) struct-access operator works on G.
No idea why anyone would do this. I would think it much cleaner to convert to/from the character array when that is needed (which is "never" in the example code, but presumably it's used somewhere in the larger original code base), or use a union to get rid of the macro.
union {
struct {
int value;
/* ... */
} s;
char c[2];
} G;
G.s.value = 233; /* and so on */
is both cleaner and clearer. Note that the char array is too small.
I have two structures:
typedef struct abc {
unsigned int pref;
unsigned int port;
char *aRecordIp;
int index;
int count;
}abc_t;
typedef struct xyz {
abc_t *ab;
int index;
int count;
}xyz_t;
and I would like to achieve the following
int Lookup (char *lookup,void *handle) {
*handle = (xyz_t *)malloc(sizeof(xyz_t *));
handle->ab = (abc_t *) malloc(sizeof(abc_t *));
//
}
I am trying to typecast void pointer to xyz_t basically.
Is this correct?
You are doing it wrong on multiple counts:
You're trying to set a variable handle->ab, but handle is a void *, not a structure type pointer.
You need to show your call, but there's likely to be problems — why do you think a void * argument is a good idea?
You want to allocate structures, so the sizeof() operands should be xyz_t and not xyz_t *; repeat for abc_t.
You should probably use:
int Lookup(const char *lookup, xyz_t **handle)
{
...
*handle = (xyz_t *)malloc(sizeof(xyz_t));
(*handle)->ab = (abc_t *)malloc(sizeof(abc_t));
...
}
Don't forget to check the result of malloc().
There are those who will castigate you for using casts on malloc(). I won't. When I learned C (a long time ago, years before there was a C standard), on a machine where the int * value for an address was not the same bit pattern as the char * address for the same memory location, where malloc() had to be declared char *malloc() or all hell broke loose, the casts were necessary. But — and this is the major issue that people are concerned about — it is crucial that you compile with compiler options such that if you invoke a function without a prototype in scope, you will get a compilation error, or a warning that you will pay attention to. The concern is that if you do not have a declaration for malloc() in scope, you will get incorrect results from using the cast which the compiler would diagnose if you don't.
On the whole, though, I think you should separate your lookup code from your 'create xyz_t' code — your function is doing two jobs and it complicates the interface to your function.
xyz_t *Create_xyz(void);
int Lookup(const char *lookup, const xyz_t *handle);
While casting of a void* to any pointer type is correct, it is not necessary in C, and it is not recommended for malloc (e.g. see Do I cast the result of malloc? ).
Also, you should specify sizeof(xyz_t), not sieof(xyz_t*), otherwise you allocate memory enough only for pointer, not for the whole structure.
And of course you should assign a pointer to handle, not to *handle. And handle should be of proper pointer type (xyz_t*).
Oh, and if the question is about casting handle to xyz_t*, then you can do it like ((xyz_t*)handle)->ab.
I'd recommend reading a book before playing with pointers like that.
I believe you want handle to hold a valid address of a xyz_t struct after the function call. Then you need to change the function signature and contents like so:
int Lookup (char *lookup, xyz_t **handle) { // double indirection here
*handle = (xyz_t *)malloc(sizeof(xyz_t));
(*handle)->ab = (abc_t *) malloc(sizeof(abc_t));
}
And call it like this:
xyz_t *myhandle;
char lookup;
Lookup(&lookup, &mynandle);
// now you can use it
myhandle->index ...
You will need to free the memory as well...
free(myhandle->ab);
free(myhandle);
If you want to pass void *, here is the solution
int Lookup (char *lookup, void *handle) {
handle = malloc(sizeof(xyz_t));
((xyz_t *)handle)->ab = (abc_t *) malloc(sizeof(abc_t));
//
}