c code: error in the syntax of structs and their fields - c

So i wrote the following code.
NameOfStruct *S;
if (statement) {
S = (S)->property[10];
}
I defined the structure beforehand. So the error i am getting is this:
'*S' is a pointer; did you mean to use '->'? and then the line where i typed the code. I find this weird since they ask me if i meant -> while that is exactly what i use. If i instead use the following code
S = (*S)->property[10]
then i get that that there is a wrong assignment with an incompatible pointer type.
What is happening here?

Your question is kind of hard to understand, but I think I understood enough to help you.
I think your problem might be in the way you defined the struct, and not on the code that uses it.
Firstly, I don't know what NameOfStructis, so i'll define one in this example:
typedef struct test {
int someValue;
char someString[10];
}EXAMPLE;
What this does is define a struct. You can either call for struct test or EXAMPLE when you want to do something with that struct.
Now, when it comes to use that struct, you can only use -> when you are dealing with pointers. Also, when using Structs, you should allocate memory using malloc().
In your main, you should have something like this:
int main () {
//Declare pointer to struct and allocate memory.
EXAMPLE *test = (EXAMPLE*) malloc(sizeof(EXAMPLE));
//Manipulate data on struct
test->someValue = 10;
test->someString = "Testing";
free(test);
}
This way, you should be left with a struct where on someValue the content is 10and on someString the content is Testing
Also, if in your main you don't feel like using EXAMPLE you can also just use struct test. Don't forget to free the memory you allocated when you don't need it anymore.
PS: Please, next time you ask a question be sure to give a good explanation on what the problem is, show us what your attempt was, and give us the input/output you were expecting paired with the input/output that you got. If you're left with any questions, feel free to reply to this answer and I'll try to help you

Related

C - How to free a struct array cell completely

I read some other questions like this here on stack overflow, and I fixed the problem I had with my use of free();
I have a struct array of this type:
typedef struct _event {
char* desc;
int start;
int end;
} event;
But it seems I can only free the desc, while if I try to use the free for the two integers (start/end), it doesn't work.
Reading the other answers in other posts, I understood that I can't free something I haven't malloc'd. The point is: I don't need to malloc() an integer. But on my exercise, I really need to erase that array block. (I don't mean the whole array, just that block).
I don't want to put much code in this post to don't bother the reader, but if you need please tell me!
At the moment I am using:
free(event[i].desc);
in a for loop under a certain if statement.
The question is how to free also event[i].start and event[i].end ?
Thank you in advance, I am sorry about the dumb question, but I wanted to know if it is possible to free the entire cell instead of using a marker like '0'.
P.S. If you know a good article or tutorial about free() function, can you please link it to me?
If you allocated event as a block, e.g.
event * p = (event *) malloc(sizeof(event);
p->desc = (char *) malloc (sizeof(char) * SIZE); // presume SIZE defined earlier
then, you could free in reverse sequence as below:
free(p->desc);
free(p); // will deallocate the entire block
Hope this is what you meant to know.
It is important to understand that you cannot free just a part of your structure:
In your case you have a pointer on char and 2 int.
The char* can store an address you get via malloc: this can be freed. But the 2 int cannot.
If for some reason they became irrelevant and you really need to get rid of these variables, then you probably defined your structure the wrong way: you might want to split it.
An other solution could be to reset these fields with a default value (like 0 or -1 or whatever you define), and free the  char * as #Debasish Jana explained.

Issues with malloc in C

I seem to be having some issues with malloc in my code. Here's what's going on.
I've got a struct created with a few values in it. From there, I'd like to make an array of structs. I think I've got the struct right, and some of the pointers, but I'm not sure.
Here's the struct:
typedef struct{
char name[25];
int courseID;
} course;
From there, I try to initiate the new struct and malloc it at the same time by this:
course *courses = malloc(25*sizeof(course));
From here, I'm getting the error:
Invalid conversion from 'void*' to 'course*' [-fpermissive] course
*courses = malloc(25*sizeof(course));
I don't really know what this means... I know I may be completely off course with this whole idea, so any help y'all can give would be great!
You must be using a C++ compiler. You want to compile with a C compiler.
Make sure your file name ends in .c not .cpp or .cc.
You also said you try to initialize (you said initiate but I am translating) the new struct. Malloc will not do that. Malloc allocated memory will contain random values left over from the last user of that memory. The calloc function might work better for what you want since it sets the memory to zero after allocating it.
You are initializing memory with malloc, which returns a void pointer to the allocated memory. You are then assigning this pointer to a course pointer. So there is a pointer mismatch and hence the warning. To bypass it use
course *courses = (course *)malloc(25 * sizeof(course))

Why use address of first element of struct, rather than struct itself?

I've just come upon yet another code base at work where developers consistently use the address of the first element of structs when copying/comparing/setting, rather than the struct itself. Here's a simple example.
First there's a struct type:
typedef struct {
int a;
int b;
} foo_t;
Then there's a function that makes a copy of such a struct:
void bar(foo_t *inp)
{
foo_t l;
...
memcpy(&l.a, &inp->a, sizeof(foo_t));
...
}
I wouldn't myself write a call to memcpy in that way and I started out with suspecting that the original developers simply didn't quite grasp pointers and structs in C. However, now I've seen this in two unrelated code bases, with no common developers so I'm starting to doubt myself.
Why would one want to use this style?
Nobody should do that.
If you rearrange struct members you are in trouble.
Instead of that:
memcpy(&l.a, &inp->a, sizeof(foo_t));
you can do that:
memcpy(&l, inp, sizeof(foo_t));
While it can be dangerous and misleading, both statements actually do the same thing here as C guarantees there is no padding before the first structure member.
But the best is just to copy the structure objects using a simple assignment operator:
l = *inp;
Why would one want to use this style?
My guess: ignorance or bad discipline.
One wouldn't. If you ever moved a in the struct or you inserted member(s) before it, you would introduce a memory smashing bug.
This code is unsafe because rearranging the members of the struct can result in the memcpy accessing beyond the bounds of the struct if member a is no longer the first member.
However, it's conceivable that members are intentionally ordered within the struct and programmer only wants to copy a subset of them, beginning with member a and running until the end of the struct. If that's the case then the code can be made safe with the following change:
memcpy(&l.a, &inp->a, sizeof(foo_t) - offsetof(foo_t, a));
Now the struct members may be rearranged into any order and this memcpy will never go out of bounds.
Actually, there is one legitimate use case for this: constructing a class hierarchy.
When treating structs as a class instances, the first member (i.e. offset 0) will typically be the supertype instance... if a supertype exists. This allows a simple cast to move between using the subtype vs. the supertype. Very useful.
On Darren Stone's note about intention, this is expected when executing OO in the C language.
In any other case, I would suggest avoiding this pattern and accessing the member directly instead, for reasons already cited.
It's a really bad habit. The struct might have another member prepended, for example. This is an insanely careless habit and I am surprised to read that anyone would do this.
Others have already noted these; the one that bugs me is this:
struct Foo rgFoo [3];
struct Foo *pfoo = &rgFoo [0];
instead of
struct Foo *pfoo = rgfoo;
Why deref the array by index and then take the address again? It's already the address, the only difference of note is that pfoo is technically
struct Foo *const,
not
struct Foo *.
Yet I used to see the first one all the time.

pointer to structure confusion in C

I've written some code that doesn't want to work, and after much thought I've decided that the cause of all my trouble is a loop that is trying to copy strings to an array, which is a component of a structure, pointed to by a pointer passed to the function.
This isn't exactly my code, but whatever is making this not work is also making my code not work:
typedef struct {
int A[100];
} thing;
this something vaguely like the structure I'm using.
Then within the main function:
thing *s;
int i;
for (i=0;i<5;i++) {
s->A[i]=i;
}
So, this doesn't work. Much to my dismay and confusion, however, this does:
thing *s;
s->A[0]=0;
s->A[1]=1;
s->A[2]=2;
s->A[3]=3;
s->A[4]=4;
Concerning this, I am at a loss, and have spent much time indeed trying to find a solution for myself. I know I'm missing something here, I just hope it's not obvious
That's undefined behavior; there is no object behind that pointer -- the result could be anything. Undefined behavior can appear to work, or it can fail in very mysterious ways.
You could approach it like this:
thing th;
thing* s = &th;
...now 's' points to a 'thing' -- specifically, 'th'.

Resizing a char[x] to char[y] at runtime

OK, I hope I explain this one correctly.
I have a struct:
typedef struct _MyData
{
char Data[256];
int Index;
} MyData;
Now, I run into a problem. Most of the time MyData.Data is OK with 256, but in some cases I need to expand the amount of chars it can hold to different sizes.
I can't use a pointer.
Is there any way to resize Data at run time? How?
Code is appreciated.
EDIT 1:
While I am very thankful for all the comments, the "maybe try this..." or "do that", or "what you are dong is wrong..." comments are not helping. Code is the help here. Please, if you know the answer post the code.
Please note that:
I cannot use pointers. Please don't try to figure out why, I just can't.
The struct is being injected into another program's memory that's why no pointers can be used.
Sorry for being a bit rough here but I asked the question here because I already tried all the different approaches that thought might work.
Again, I am looking for code. At this point I am not interested in "might work..." or " have you considered this..."
Thank you and my apologies again.
EDIT 2
Why was this set as answered?
You can use a flexible array member
typedef struct _MyData
{
int Index;
char Data[];
} MyData;
So that you can then allocate the right amount of space
MyData *d = malloc(sizeof *d + sizeof(char[100]));
d->Data[0..99] = ...;
Later, you can free, and allocate another chunk of memory and make a pointer to MyData point to it, at which time you will have more / less elements in the flexible array member (realloc). Note that you will have to save the length somewhere, too.
In Pre-C99 times, there isn't a flexible array member: char Data[] is simply regarded as an array with incomplete type, and the compiler would moan about that. Here i recommend you two possible ways out there
Using a pointer: char *Data and make it point to the allocated memory. This won't be as convenient as using the embedded array, because you will possibly need to have two allocations: One for the struct, and one for the memory pointed to by the pointer. You can also have the struct allocated on the stack instead, if the situation in your program allows this.
Using a char Data[1] instead, but treat it as if it were bigger, so that it overlays the whole allocated object. This is formally undefined behavior, but is a common technique, so it's probably safe to use with your compiler.
The problem here is your statement "I can't use a pointer". You will have to, and it will make everything much easier. Hey, realloc even copies your existing data, what do you want more?
So why do you think you can't use a pointer? Better try to fix that.
You would re-arrange the structure like that
typedef struct _MyData
{
int Index;
char Data[256];
} MyData;
And allocate instances with malloc/realloc like that:
my_data = (MyData*) malloc ( sizeof(MyData) + extra_space_needed );
This is an ugly approach and I would not recommend it (I would use pointers), but is an answer to your question how to do it without a pointer.
A limitation is that it allows for only one variable size member per struct, and has to be at the end.
Let me sum up two important points I see in this thread:
The structure is used to interact between two programs through some IPC mechanism
The destination program cannot be changed
You cannot therefore change that structure in any way, because the destination program is stuck trying to read it as currently defined. I'm afraid you are stuck.
You can try to find ways to get the equivalent behavior, or find some evil hack to force the destination program to read a new structure (e.g., modifying the binary offsets in the executable). That's all pretty application specific so I can't give much better guidance than that.
You might consider writing a third program to act as an interface between the two. It can take the "long" messages and do something with them, and pass the "short" messages onward to the old program. You can inject that in between the IPC mechanisms fairly easily.
You may be able to do this like this, without allocating a pointer for the array:
typedef struct _MyData
{
int Index;
char Data[1];
} MyData;
Later, you allocate like this:
int bcount = 256;
MyData *foo;
foo = (MyData *)malloc(sizeof(*foo) + bcount);
realloc:
int newbcount = 512;
MyData *resized_foo;
resized_foo = realloc((void *)foo, sizeof(*foo) + newbcount);
It looks like from what you're saying that you definitely have to keep MyData as a static block of data. In which case I think the only option open to you is to somehow (optionally) chain these data structures together in a way that can be re-assembled be the other process.
You'd need and additional member in MyData, eg.
typedef struct _MyData
{
int Sequence;
char Data[256];
int Index;
} MyData;
Where Sequence identifies the descending sequence in which to re-assemble the data (a sequence number of zero would indicate the final data buffer).
The problem is in the way you're putting the question. Don't think about C semantics: instead, think like a hacker. Explain exactly how you are currently getting your data into the other process at the right time, and also how the other program knows where the data begins and ends. Is the other program expecting a null-terminated string? If you declare your struct with a char[300] does the other program crash?
You see, when you say "passing data" to the other program, you might be [a] tricking the other process into copying what you put in front of it, [b] tricking the other program into letting you overwrite its normally 'private' memory, or [c] some other approach. No matter which is the case, if the other program can take your larger data, there is a way to get it to them.
I find KIV's trick quite usable. Though, I would suggest investigating the pointer issue first.
If you look at the malloc implementations
(check this IBM article, Listing 5: Pseudo-code for the main allocator),
When you allocate, the memory manager allocates a control header and
then free space following it based on your requested size.
This is very much like saying,
typedef struct _MyData
{
int size;
char Data[1]; // we are going to break the array-bound up-to size length
} MyData;
Now, your problem is,
How do you pass such a (mis-sized?) structure to this other process?
That brings us the the question,
How does the other process figure out the size of this data?
I would expect a length field as part of the communication.
If you have all that, whats wrong with passing a pointer to the other process?
Will the other process identify the difference between a pointer to a
structure and that to a allocated memory?
You cant reacolate manualy.
You can do some tricks wich i was uning when i was working aon simple data holding sistem. (very simple filesystem).
typedef struct
{
int index ;
char x[250];
} data_ztorage_250_char;
typedef struct
{
int index;
char x[1000];
} data_ztorage_1000_char;
int main(void)
{
char just_raw_data[sizeof(data_ztorage_1000_char)];
data_ztorage_1000_char* big_struct;
data_ztorage_250_char* small_struct;
big_struct = (data_ztorage_1000_char*)big_struct; //now you have bigg struct
// notice that upper line is same as writing
// big_struct = (data_ztorage_1000_char*)(&just_raw_data[0]);
small_struct = (data_ztorage_250_char*)just_raw_data;//now you have small struct
//both structs starts at same locations and they share same memory
//addresing data is
small_struct -> index = 250;
}
You don't state what the Index value is for.
As I understand it you are passing data to another program using the structure shown.
Is there a reason why you can't break your data to send into chunks of 256bytes and then set the index value accordingly? e.g.
Data is 512 bytes so you send one struct with the first 256 bytes and index=0, then another with the next 256 bytes in your array and Index=1.
How about a really, really simple solution? Could you do:
typedef struct _MyData
{
char Data[1024];
int Index;
} MyData;
I have a feeling I know your response will be "No, because the other program I don't have control over expects 256 bytes"... And if that is indeed your answer to my answer, then my answer becomes: this is impossible.

Resources