473,668 Members | 2,616 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

struct manipulation

Hello folks
I hope code below will explain what I'm trying to achive.
It seems trivial/common but not for me at the moment :(
Help very apreciated.
Regards
Darek.
-----------------
#include <windows.h>
#include <stdio.h>
#include <tchar.h>

typedef struct Test {
char name[128];
int count;
};

int test(Test *t);

int test(Test *t)
{
Test *loct = t;
t = (Test *)HeapAlloc(Get ProcessHeap(), HEAP_ZERO_MEMOR Y, sizeof(Test));
strcpy(t->name,"TestEntr y");
t->count = 256;
//? so address of t has been changed, is there a way to assign struct
values to old one?

return 0;
}

int main()
{
Test *t;
char out[128];
test(t);
// Is there a way to get values passed to t?
// now of course printf statement doesnt print proper string value
printf("%s",t->name);
return 0;
}

Nov 13 '05 #1
5 9951
Darek Adamkiewicz <d.***********@ i7.com.pl> wrote:
#include <windows.h>
This is not an ISO C header, so it's off-topic here.
#include <stdio.h>
#include <tchar.h>
Ditto.
typedef struct Test {
char name[128];
int count;
};

int test(Test *t);

int test(Test *t)
{
Test *loct = t;
t = (Test *)HeapAlloc(Get ProcessHeap(), HEAP_ZERO_MEMOR Y, sizeof(Test));
Neither HeapAlloc() not GetProcessHeap is an ISO C function, so they're
off-topic here.
Even so, you probably want

t = HeapAlloc(GetPr ocessHeap(), HEAP_ZERO_MEMOR Y, sizeof *t);

since casts are rarely necessary for properly declared allocation
functions in C, and sizeof *pointer_i'm_al locating_for means less
maintenance than sizeof (some_type) in case the type of the pointer
changes.
strcpy(t->name,"TestEntr y");
t->count = 256;
//? so address of t has been changed, is there a way to assign struct
values to old one?
Sure. You've taken the precaution of saving the old value of t in loct;
since you didn't change it when you changed t, it still points at the
old address.

Note, however, that you never pass the new value of t outside of this
function, and don't free the allocated memory, either; this means that
you have, in all probability, created a memory leak. (I say in all
probability, because, HeapAlloc() not being ISO C, there is no saying
what it might be doing behind the screens - including, for example,
keeping a global record of HeapAlloc()ated pointers. Had you use
malloc(), I'd have been sure that this _is_ a memory leak.)
Note that a pointer is just an object, not something magical: passing
one to a function and then changing its value inside that function will
not change the value in the caller any more than doing the same thing to
an int will. See the FAQ: <http://www.eskimo.com/~scs/C-faq/q4.8.html>.
int main()
{
Test *t;
char out[128];
test(t);
// Is there a way to get values passed to t?


t is an object; one doesn't "pass" values to objects. One passes values
to functions, and assigns them to objects. But see the FAQ entry above.

Richard
Nov 13 '05 #2
Richard Bos wrote:
See the FAQ: <http://www.eskimo.com/~scs/C-faq/q4.8.html>.

So while I can do the following (is it correct?)
--------------------------
#include <stdio.h>

void f(int *ip);

void f(int *ip)
{
static int dummy = 5;
*ip = dummy;
}

int main()
{
int *ip;
f(ip);
printf("%d\n", *ip);
}
--------------------
I can't do similar with struct in C? - pass struct pointer to function,
declare local struct, allocate memory, set values to and finally make
that pointer address contain pointer to that struct?

Regards
Darek

Nov 13 '05 #3
In <bd**********@n emesis.news.tpi .pl> Darek Adamkiewicz <d.***********@ i7.com.pl> writes:
I hope code below will explain what I'm trying to achive.
I'm afraid you're overoptimistic. The code below doesn't make any sense.
#include <windows.h>
Undefined behaviour.
#include <stdio.h>
#include <tchar.h>
Undefined behaviour.
typedef struct Test {
char name[128];
int count;
};

int test(Test *t);
Pointless declaration.
int test(Test *t)
Why make test() return int, if it doesn't return anything useful to its
caller?
{
Test *loct = t;
t = (Test *)HeapAlloc(Get ProcessHeap(), HEAP_ZERO_MEMOR Y, sizeof(Test));
There is no such function in the standard C library. When posting to this
newsgroup, use malloc(), declared in <stdlib.h>, so that we can figure out
what exactly you're trying to do.
strcpy(t->name,"TestEntr y");
Undefined behaviour: strcpy is not a function returning int and you have
provided no declaration for it. Include <string.h>.
t->count = 256;
//? so address of t has been changed, is there a way to assign struct
values to old one?
Nope, the address of t has not changed and it cannot change. If you're
talking about the *value* of t, you have saved the original value in
loct and you can use it.
return 0;
}
Note that the new value assigned to t in test() gets lost at this point.
The object allocated in test() becomes a memory leak, because its address
is lost forever.
int main()
{
Test *t;
char out[128];
test(t);
You have NOT initialised t. What's the point of passing an indeterminate
value to the test() function. If you don't understand what I mean, read
the FAQ asap.
// Is there a way to get values passed to t?
Yes, if t is initialised, test() can store something into the object it
points to. But your test() doesn't even try...
// now of course printf statement doesnt print proper string value
Obviously, because:

1. t was passed to test() uninitialised.

2. test() saved the original value of t, but didn't attempt to do anything
else with it.
printf("%s",t->name);
return 0;
}


You really need to read the chapter dealing with functions in your
favourite C book. You don't seem to understand how function argument
passing works in C. And the way you handle t in main() denotes a lack of
basic understanding about pointer usage, too.

At your level, it makes *absolutely* NO sense to mess with Windows
programming. Restrict yourself to the basic features of the C language.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #4
You'll be surprised but I read K&R book and wrote some working till
today C ANSI programs about 3 years ago - It's seems I forgot almost
everything I learned :( or overrode by perl data manipulation techniques
which allow programmer to do (almost) everything he/she wants. Thanks
anyway - I must do "my homework" again :(

Regards
Darek

Nov 13 '05 #5
Darek Adamkiewicz <d.***********@ i7.com.pl> wrote:
Richard Bos wrote:
See the FAQ: <http://www.eskimo.com/~scs/C-faq/q4.8.html>. So while I can do the following (is it correct?)
--------------------------
#include <stdio.h>

void f(int *ip);

void f(int *ip)
{
static int dummy = 5;
*ip = dummy;
}

int main()
{
int *ip;
f(ip);
printf("%d\n", *ip);
}


That's almost correct. Point ip at a valid int before you pass it to
f(), then it's correct.
I can't do similar with struct in C?


Wrong. This

#include <stdio.h>

struct st {
int i;
};

void f(struct st *stp)
{
struct st dummy={5}
*stp=dummy;
}

int main()
{
struct st temp;
f(&temp);
printf("%d\n", temp.i);
}

is perfectly legal.

However, it isn't what you were doing in the original post. There, the
object you modified in f() was a pointer. Not the struct the pointer
pointed to - the pointer itself.
As the FAQ explains, if you wish to change _anything_ in a function, you
must pass a pointer to it. So if the object you want to change is a
pointer, you must pass a pointer _to_ that pointer. Like this:

#include <stdio.h>

struct st {
int i;
};

void f(struct st **stp)
{
struct st dummy={5}

*stp=malloc(siz eof **stp);
if (*stp)
**stp=dummy;
}

int main()
{
struct st *stp_pointer;
f(&stp_pointer) ;

if (stp_pointer)
printf("%d\n", stp_pointer->i);
else
puts("Null pointer - allocation failure.");

free(stp_pointe r);
}

Richard
Nov 13 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3436
by: Alex | last post by:
How can I make a simple Struct in ASP ? I saw a other post and it sound like "PAIN!" struct s_my_table { $name, $sexe, $age, }
15
9054
by: Steven T. Hatton | last post by:
The following may strike many of you as just plain silly, but it represents the kind of delelima I find myself in when trying to make a design decision. This really is a toy project written for the purpose of learning to work with C++. It therefore makes some sense for me to give the situation the amount of consideration presented below. To be quite honest, I'm amazed at the amount there is to say about such a seemingly simple...
9
2587
by: I. Kobrinsky | last post by:
I'm new here. I started a personal password-program, a trial that includes username, logincounter and password. So my intention is to hide pwd while tipping. So I'm thinking about two popular ways to realize, like using cursor manipulation to backup & delete letters or otherwise to use getch to read them quetly. Maybe somebody here knows and will tell me about potentially dis-/advantages of each method. Meaning especially *intern*
8
5797
by: Luc Le Blanc | last post by:
I have 2 APIs that store/recall a void *. Since all I need to store is a 32-bit struct, I pass the actual data (instead of a pointer to it) as a void *: typedef { UInt8 color; UInt8 index; UInt16 resID; } GadgetData;
15
43539
by: Ken Allen | last post by:
I have some code from C/C++ that I am attempting to port to C#. I have come across an interesting problem that is quite common in complex C/C++ code: the us of UNION in structure definitions to permit the same piece of memory to be referenced as different data types. This is often used to save space and permit a single piece of memory to contain different types of data, typically based on some other flag in the structure. In other cases...
9
2139
by: Job | last post by:
Hi, I would like to find out what ASP/ASP.net can do with image manipulation. Does ASP have built in functions (eg. after upload to server) to manipulate images, like rotate, scale, crop etc.? Or are 3rd party solutions needed to do this? I am a php/codfusion programmer and know nothing about asp, so I'm hoping somebody here can help me out.
3
2749
by: Ashutosh | last post by:
Hello, I am a newbie in CSharp. In C++ if we want to read from socket into the struct object we directly type cast it as recv(socketid,(char*),&struct_object,sizeof(struct object)) But C Sharp does not allow such thing.
0
2577
by: L'eau Prosper Research | last post by:
Press Release: L'eau Prosper Research (Website: http://www.leauprosper.com) releases new TradeStation 8 Add-on - L'eau Prosper Market Manipulation Profiling Tools Set. L'eau Prosper Market Manipulation Profiling Tools Set is a set of advanced tools that help Serious Traders analyze the market direction, market manipulative behavior and predicting the change of trend.
0
2342
by: L'eau Prosper Research | last post by:
NEW TradeStation 8 Add-on - L'eau Prosper Market Manipulation Profiling Tools Set By L'eau Prosper Research Press Release: L'eau Prosper Research (Website: http://www.leauprosper.com) releases new TradeStation 8 Add-on - L'eau Prosper Market Manipulation Profiling Tools Set. L'eau Prosper Market Manipulation Profiling Tools Set is a set of
0
8459
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8367
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8790
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8650
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7391
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4202
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2781
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2017
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1779
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.