A question with the same title has been asked before on Stack Overflow but it isn't the answer I am a looking for.
I am trying to create a pointer to a dynamically-allocated array containing the pixel data.
This is how I try doing it.
struct Image {
int width;
int height;
int* pixels = malloc((width * height) * sizeof(int));
};
Error Message
But I am getting an error expected a ';'
The same code outside the struct works fine.
Can someone please explain to me why this errror occurs.
The same code outside the struct works fine.
Can someone please explain to me why this errror occurs.
This is because a struct in C is something different than a struct C#:
In C you cannot assign "default" values to struct members like this:
struct myStruct {
int a = 2;
int b = 4;
};
You can only assign initial constant values to a variable that has a struct type:
struct mystruct {
int a;
int b;
};
struct mystruct myvar = { 5, 6 }; /* myvar.a=5, myvar.b=6 */
... but because malloc() is a function call, the following line is also not possible in C:
struct Image myVariable = { 10, 20, malloc(200) };
You must initialize the field pixels "outside the struct".
Related
#include<stdio.h>
struct a
{
float n;
int e;
};
struct b
{
struct a *c;
}h;
int main()
{
h.c->n=4;
printf("%f",h.c->n);
return 0;
}
Yes it is small code but I have been trying to access the element e which is instruct a through the struct b. The code is compiled without any error but in the output screen, it is blank.
Please suggest me a good way to access the element in the struct a.
Please note that the struct a has been declared inside the struct b as a pointer.
This would crash because your pointer c was never allocated.
h.c->n=4; // pointer `c` has not been pointing to anything valid
To make it work, you need something like this:
struct a aa; // must allocate an item of struct `a` first
aa.n = 4;
aa.e = 0;
h.c = &aa; // then make pointer `c` to point that that item
printf("%f",h.c->n); // before trying to access that pointer
I tried to use an external struct but when I compile my c code I obtained this message:
subscripted value is neither array nor pointer nor vector.
Why?
messaggio.h
struct Request {
struct {
u_int data_len;
float *data_val;
} data;
bool_t last;
};
typedef struct Request Request;
main.c
#include "messaggio.h"
int main(void){
struct Request x;
x.data[0] = 4.6;
printf("%f\n",x.data[0]);
return 0;
}
The x.data is a struct, so you cannot use [] with it. Maybe you want x.data.data_val[0].
Try this code:
struct Request x;
x.data.data_len = 5; // initialize the length, use any value you need
x.data.data_val = (float *) malloc(x.data.data_len * sizeof(float));
x.data.data_val[0] = 4.6
x.data is a structure and not an array.
Use x.data.data_val[0] if that is what you are trying to access. However, you have not allocated any memory for data_val. I believe you are trying to assign a number to data_len and will need to allocate the memory to hold data_len values in data_val.
The type of struct Request#data is an anonymous struct { u_int, float } and not an array. Thus you can't use the [] operator on it.
You probably wanted to do:
x.data.data_val[0]
I've got a function that takes as an argument a pointer to an array of structs:
void foo (int *StructArrayAddress)
Within the function, I then build a new struct that looks like this
struct
{
int a;
int b;
char c[10];
}myStruct;
What I would then like to do is copy that struct to my array of structs based on the pointer to that array that I received as an argument. Not having any luck with the syntax, or I'm missing something. Can anyone advise?
Thanks!
EDIT: I'm not sure I explained myself correctly, as I don't think the solution posted here is what I want to do. To clarify: there is some array of structs outside my function here. I receive the address of the correct struct element in an array of structs as an argument to my function. Assume the caller already took care of passing me the correct address; I don't have to index it up at all.
I then locally build a struct from some other data. I now want to copy this struct that I built locally to the struct at the location in the array that I received as an argument.
void foo (int *StructArrayAddress)
{
struct
{
int a;
int b;
char c[10];
}myStruct;
a = 5;
b = 10;
c = {1,2,3,4,5,6,7,8,9,10};
//Copy local struct myStruct to location StructArrayAddress here
StructArrayAddress = myStruct; //Something like this but I have the syntax wrong
}
I hope that makes more sense.
EDIT2: I may have just realized something that you guys have been trying to convey to me that I was missing: is a reference to my local struct needed in the argument somehow so that the format of the structure as I pass it back is known?
Your function definition should be like
void foo (myStruct *StructArrayAddress, int index)
{
myStruct x;
x.a = 1;
x.b = 2;
strncpy(x.c, "Test", 9);
/* Now copy this struct to the array of structs at index specified by second argument */
memcpy((StructArrayAddress + index), &x, sizeof(myStruct));
}
This code:
extern void *malloc(unsigned int);
struct Box {
int x, y ,w, h;
};
struct Wall {
char color[15];
struct Box *boxes[20];
};
int main(int argc, const char *argv[])
{
struct Wall *mywall = malloc(sizeof(struct Wall));
struct Box *myboxes[] = mywall->boxes;
return 0;
}
gives me invalid initializer error at line 14. What I am trying to do, is to get a copy of array of struct pointers, which are in a different struct.
Ouch; there are a number of problems here.
extern void *malloc(unsigned int);
Don't do that; use #include <stdlib.h> because that will be correct and what you wrote is typically incorrect (the argument to malloc() is a size_t, which is not necessarily an unsigned int; it might be unsigned long, or some other type).
struct Box {
int x, y ,w, h;
};
Apart from erratic space, struct Box is OK.
struct Wall {
char color[15];
struct Box *boxes[20];
};
And struct Wall is OK too.
int main(int argc, const char *argv[])
You aren't using argc or argv, so you'd be better using the alternative declaration of:
int main(void)
Original code again:
{
struct Wall *mywall = malloc(sizeof(struct Wall));
This allocates but does not initialize a single struct Wall. Of itself, it is OK, though you should check that the allocation succeeded before you use it. You also need to worry about allocating the struct Box items that the elements of the array will point to.
struct Box *myboxes[] = mywall->boxes;
You've got a minor catastrophe on hand here. You can't copy arrays like that. You haven't checked that you've got an array. Ignoring the error checking, you are stuck with one of:
struct Box *myboxes[] = { &mywall->boxes[0], &mywall->boxes[1], ... };
or:
struct Box **myboxes = &mywall->boxes;
I'm not convinced that you'd want the second version, for all it's shorter.
return 0;
I like to see return 0; at the end of main(), even though C99 allows you to omit it.
}
How about:
struct Box **myboxes = mywall->boxes;
?
Then you can do stuff like:
for ( int i = 0 ; i < 15 ; i++ )
mywall->boxes[i] = malloc(sizeof(Box));
Box* x = myboxes[1];
As the code is now, mywall->boxes isn't initialized.
NOTE: just re-read the question - this won't return a copy of the array, but point to the same location. There's no short solution for a copy without using memcpy or just copying the structs.
Is there an easy explanation for what this error means?
request for member '*******' in something not a structure or union
I've encountered it several times in the time that I've been learning C, but I haven't got a clue as to what it means.
It also happens if you're trying to access an instance when you have a pointer, and vice versa:
struct foo
{
int x, y, z;
};
struct foo a, *b = &a;
b.x = 12; /* This will generate the error, should be b->x or (*b).x */
As pointed out in a comment, this can be made excruciating if someone goes and typedefs a pointer, i.e. includes the * in a typedef, like so:
typedef struct foo* Foo;
Because then you get code that looks like it's dealing with instances, when in fact it's dealing with pointers:
Foo a_foo = get_a_brand_new_foo();
a_foo->field = FANTASTIC_VALUE;
Note how the above looks as if it should be written a_foo.field, but that would fail since Foo is a pointer to struct. I strongly recommend against typedef:ed pointers in C. Pointers are important, don't hide your asterisks. Let them shine.
You are trying to access a member of a structure, but in something that is not a structure. For example:
struct {
int a;
int b;
} foo;
int fum;
fum.d = 5;
It may also happen in the following case:
eg. if we consider the push function of a stack:
typedef struct stack
{
int a[20];
int head;
}stack;
void push(stack **s)
{
int data;
printf("Enter data:");
scanf("%d",&(*s->a[++*s->head])); /* this is where the error is*/
}
main()
{
stack *s;
s=(stack *)calloc(1,sizeof(stack));
s->head=-1;
push(&s);
return 0;
}
The error is in the push function and in the commented line. The pointer s has to be included within the parentheses. The correct code:
scanf("%d",&( (*s)->a[++(*s)->head]));
I have enumerated possibly all cases where this error may occur in code and its comments below. Please add to it, if you come across more cases.
#include<stdio.h>
#include<malloc.h>
typedef struct AStruct TypedefedStruct;
struct AStruct
{
int member;
};
void main()
{
/* Case 1
============================================================================
Use (->) operator to access structure member with structure pointer, instead
of dot (.) operator.
*/
struct AStruct *aStructObjPtr = (struct AStruct *)malloc(sizeof(struct AStruct));
//aStructObjPtr.member = 1; //Error: request for member ‘member’ in something not
//a structure or union.
//It should be as below.
aStructObjPtr->member = 1;
printf("%d",aStructObjPtr->member); //1
/* Case 2
============================================================================
We can use dot (.) operator with struct variable to access its members, but
not with with struct pointer. But we have to ensure we dont forget to wrap
pointer variable inside brackets.
*/
//*aStructObjPtr.member = 2; //Error, should be as below.
(*aStructObjPtr).member = 2;
printf("%d",(*aStructObjPtr).member); //2
/* Case 3
=============================================================================
Use (->) operator to access structure member with typedefed structure pointer,
instead of dot (.) operator.
*/
TypedefedStruct *typedefStructObjPtr = (TypedefedStruct *)malloc(sizeof(TypedefedStruct));
//typedefStructObjPtr.member=3; //Error, should be as below.
typedefStructObjPtr->member=3;
printf("%d",typedefStructObjPtr->member); //3
/* Case 4
============================================================================
We can use dot (.) operator with struct variable to access its members, but
not with with struct pointer. But we have to ensure we dont forget to wrap
pointer variable inside brackets.
*/
//*typedefStructObjPtr.member = 4; //Error, should be as below.
(*typedefStructObjPtr).member=4;
printf("%d",(*typedefStructObjPtr).member); //4
/* Case 5
============================================================================
We have to be extra carefull when dealing with pointer to pointers to
ensure that we follow all above rules.
We need to be double carefull while putting brackets around pointers.
*/
//5.1. Access via struct_ptrptr and ->
struct AStruct **aStructObjPtrPtr = &aStructObjPtr;
//*aStructObjPtrPtr->member = 5; //Error, should be as below.
(*aStructObjPtrPtr)->member = 5;
printf("%d",(*aStructObjPtrPtr)->member); //5
//5.2. Access via struct_ptrptr and .
//**aStructObjPtrPtr.member = 6; //Error, should be as below.
(**aStructObjPtrPtr).member = 6;
printf("%d",(**aStructObjPtrPtr).member); //6
//5.3. Access via typedefed_strct_ptrptr and ->
TypedefedStruct **typedefStructObjPtrPtr = &typedefStructObjPtr;
//*typedefStructObjPtrPtr->member = 7; //Error, should be as below.
(*typedefStructObjPtrPtr)->member = 7;
printf("%d",(*typedefStructObjPtrPtr)->member); //7
//5.4. Access via typedefed_strct_ptrptr and .
//**typedefStructObjPtrPtr->member = 8; //Error, should be as below.
(**typedefStructObjPtrPtr).member = 8;
printf("%d",(**typedefStructObjPtrPtr).member); //8
//5.5. All cases 5.1 to 5.4 will fail if you include incorrect number of *
// Below are examples of such usage of incorrect number *, correspnding
// to int values assigned to them
//(aStructObjPtrPtr)->member = 5; //Error
//(*aStructObjPtrPtr).member = 6; //Error
//(typedefStructObjPtrPtr)->member = 7; //Error
//(*typedefStructObjPtrPtr).member = 8; //Error
}
The underlying ideas are straight:
Use . with structure variable. (Cases 2 and 4)
Use -> with pointer to structure. (Cases 1 and 3)
If you reach structure variable or pointer to structure variable by following pointer, then wrap the pointer inside bracket: (*ptr). and (*ptr)-> vs *ptr. and *ptr-> (All cases except case 1)
If you are reaching by following pointers, ensure you have correctly reached pointer to struct or struct whichever is desired. (Case 5, especially 5.5)
It may means that you forgot include a header file that define this struct/union.
For example:
foo.h file:
typedef union
{
struct
{
uint8_t FIFO_BYTES_AVAILABLE : 4;
uint8_t STATE : 3;
uint8_t CHIP_RDY : 1;
};
uint8_t status;
} RF_CHIP_STATUS_t;
RF_CHIP_STATUS_t getStatus();
main.c file:
.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the #include "foo.h" */
.
.
.
can also appear if:
struct foo { int x, int y, int z }foo;
foo.x=12
instead of
struct foo { int x; int y; int z; }foo;
foo.x=12
I saw this when I was trying to access the members.
My struct was this:
struct test {
int a;
int b;
};
struct test testvar;
Normally we access structure members as
testvar.a;
testvar.b;
I mistook testvar to be a pointer and did this.
testvar->a;
That's when I saw this error.
request for member ‘a’ in something not a structure or union
My ridiculous experience is that I incorrectly put '.' instead of ','.
printf("%c". ch);