pointer to structure confusion in C - 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'.

Related

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

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

Can I access a member of a struct with a pointer to a struct which contains a pointer to that struct

I am trying to access the members in the struct tCAN_MESSAGE. What I think would work is like the first example in main, i.e. some_ptr->canMessage_ptr->value = 10;. But I have some code that someone else have written and what I can see is that that person have used some_ptr->canMessage_ptr[i].value;.
Is it possible to do it the first way? We are using pointers to structs which contains pointer to another struct (like the example below) quite often, but I never see the use of ptr1->ptr2->value?
typedef struct
{
int value1;
int value2;
int value3;
float value4;
}tCAN_MESSAGE;
typedef struct
{
tCAN_MESSAGE *canMessage_ptr;
}tSOMETHING;
int main(void)
{
tCAN_MESSATE var_canMessage;
tSOMETHING var_something;
tSOMETHING *some_ptr = &var_something;
some_ptr->canMessage_ptr = &var_canMessage;
some_ptr->canMessage_ptr->value1 = 10; //is this valid?
//I have some code that are doing this, ant iterating trough it with a for:
some_ptr->canMessage_ptr[i].value1; //Is this valid?
return 0
}
It's very simple: every pointer has to be set to point at a valid memory location before use. If it isn't, you can't use it. You cannot "store data inside pointers". See this:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
None of your code is valid. some_ptr isn't set to point anywhere, so it cannot be accessed, nor can its members. Similarly, some_ptr->canMessage_ptr isn't set to point anywhere either.
I am trying to access the members in the struct tCAN_MESSAGE. What I
think would work is like the first example in main, i.e.
some_ptr->canMessage_ptr->value = 10;. But I have some code that
someone else have written and what I can see is that that person have
used some_ptr->canMessage_ptr[i].value;. Is it possible to do it the
first way?
The expression
some_ptr->canMessage_ptr[i].value
is 100% equivalent to
(*(some_ptr->canMessage_ptr + i)).value
, which in turn is 100% equivalent to
(some_ptr->canMessage_ptr + i)->value
. When i is 0, that is of course equivalent to
some_ptr->canMessage_ptr->value
So yes, it is possible to use some_ptr->canMessage_ptr->value as long as the index in question is 0. If the index is always 0 then chaining arrow operators as you suggest is good style. Otherwise, the mixture of arrow and indexing operators that you see in practice would be my style recommendation.
We are using pointers to structs wich contains pointer to
another struct (like the example below) quite often, but I never see
the use of ptr1->ptr2->value ?
I'm inclined to suspect that you do not fully understand what you're working with. Usage of the form some_ptr->canMessage_ptr[i].value suggests that your tSOMETHING type contains a pointer to the first element of an array of possibly many tCAN_MESSAGEs, which is a subtle but important distinction to make. In that case, yes, as shown above, you can chain arrow operators to access the first element of such an array (at index 0). However, the cleanest syntax for accessing other elements of that array is to use the indexing operator, and it pays to be consistent.

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.

How to fix Bad Pointers in C

I am a beginner in C and as I was trying to make a simple snake game, I stumbled upon the problem of value change in pointers when used in another function. I used pointers in order to grow my snake and I used 3 of them. Granted this might be a really noobish algorithm for a snake game but I feel like I am almost there but I cannot figure out what went wrong. I have used 3 pointes for the snake itself, the x coordinate of each part of the snake and also the y. I might as well just post a part of my code.
#include<stdio.h>
#include<dos.h>
#include<conio.h>
printer(int *forgoodness,int *y,char *lang,int tx,int ty, int *x)
{
int h=*forgoodness-1,g=0;
The value changes in here, somehow the x copies 6 values of the y.
/* for(;g<15;g++)
{
printf("%i",x[g]);
}*/
for(;h>=0;h--)
{
gotoxy(x[h],y[h]);
printf("%c",lang[h]);
}
gotoxy(tx,ty);
printf(" ");
}
main()
{
int transferx=1,x=1,transfery=1,ch,game=0,dir;
int *transx, *transy, *numel;
int tempsx,g=0,tempsy,forex,j=0,*totalel;
char *snake;
int *snakey, *snakex;
If I explicitly assign values it works well but I cannot grow my snake using this:
//int snakex[15]={26,27,28,29,30,31,32,33,34,35,36,37,38,39,40};
//int snakey[15]={13,13,13,13,13,13,13,13,13,13,13,13,13,13,13};
clrscr();
*totalel=0;
*numel=14;
forex=26;
snake= "***************";
This is what I did, and I checked the values before the function printer runs and the values are fine.
for(;j<15;j++)
{
snakey[j]=13;
snakex[j]=forex;
*totalel=j;
forex++;
}
printer(numel,snakey,snake,transferx,transfery,snakex);
I hope that you can help me on this. Cheers.
Maybe attempt to rewrite a bit of your code... ideally using less pointers. Based on the code I see, it looks as if you're feeding values into random pointers. That's pretty dangerous.
For instance, doing these two lines in a row is bad:
int *num;
*num = 9;
The reason is because num is just a pointer to memory... and it isn't currently pointing to anything valid yet. The number 9 is attempting to be stored in some random location. You need to allocate some memory for num to point to, or point it to the address of another variable (a non-pointer integer). I think maybe you're not quite grasping the concepts of pointers just yet. But don't worry, it takes a little time.
You should be able to write your game without using any pointers at all, and maybe just use a fixed array for now like someone else had mentioned. Then do a bit more reading up on how pointers work and take another stab at it. I'm sure you'll get it!
But for now, try to revisit the problem with a new set of data and come back to us with what you've done so we can try to help out further. :)
Cool that you are working with pointers! But as you can see, they can be a little tricky. You have to remember that pointers are like the address of a mailbox; they can tell where something is, but they cannot (in of themselves) HOLD ANYTHING. The can just point to something that does. So every pointer you declare has to point to a real thing (like an int or an array element or an array) before it can be used or assigned to. Otherwise to are shoving values into random memory areas which causes crashes. This seems to be the main problem you are having.
int *ptr;
int value;
ptr = &value;
*ptr = 10;
// value now is 10

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