473,597 Members | 2,342 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

copying an array of pointers to structures

Hello,

Any help will be much appreciatted. My problem is as follows:

I declare as global variables:
typedef struct _Node{ ..; ..;}Node;
Node *Graph[MAX];

in a function called initiallise(), I allocate memory and copy information:
for(i )
Graph[i] = (Node*) malloc( sizeof(Node))
in main() I declare:
Node *Queue[MAX]
and I then want to copy whats in Graph (the pointers) in the Queue:
Queue = Graph

so that I can manipulate the Queue (add/remove pointers) but access it like
Queue[i]
which of course doesnt work :-(

Thanks a lot in advance.
Nov 14 '05 #1
5 2842
jimjim <dt***@mdx.ac.u k> writes:
I declare as global variables:
typedef struct _Node{ ..; ..;}Node;
Identifiers that begin with an underscore following by a capital
letter are all reserved. Pick another convention; for example,
you can simply give it Node as the tag.
Node *Graph[MAX];

in a function called initiallise(), I allocate memory and copy information:
for(i )
You'll need more than that inside your parentheses.
Graph[i] = (Node*) malloc( sizeof(Node))
When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *x = malloc (128 * sizeof (int)); /* Don't do this! */

Instead, write it this way:

int *x = malloc (128 * sizeof *x);

There's a few reasons to do it this way:

* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.

This is more of a problem in a large program, but it's still
convenient in a small one.

* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.

I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.

* If you cast to the wrong type by accident, odd failures can
result.
in main() I declare:
Node *Queue[MAX]
and I then want to copy whats in Graph (the pointers) in the Queue:
Queue = Graph
If you just want to copy the pointers, not the data pointed to,
then use memcpy:
memcpy(Queue, Graph, sizeof Queue);
Be careful: if Queue is actually a function parameter, then this
must be written as
memcpy(Queue, Graph, MAX * sizeof *Queue);
Because the latter form should always work given the declaration
above, a beginner might want to use it consistently instead of
the former.
so that I can manipulate the Queue (add/remove pointers) but access it like
Queue[i]

--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #2

Ben Pfaff thank you very much for your comments. You were very clear and I
II follow your advice.

I now have a greater problem and have no idea whats wrong :-(
As I said I declare a structure:
typedef in Vertex;
typedef struct Node{
Vertex v;
boolean known;
Distance dist;
Vertex predcssor;
}Node;

then in main() I ve got:
Node *Graph[MAX];

and create structures dynamically:
for(i=1;i<=NUMV ERTEX;i++)
Graph[i]= malloc(sizeof (*Graph));

for(i=1;i<=NUMV ERTEX;i++)
{
Graph[i]->v = i;
Graph[i]->known = NOTINTREE;
if(atoi(argv[2]) == i)
Graph[i]->dist = 0; //this is the source so set distance to zero
else
Graph[i]->dist = INFINITY; //distance from the source set to INFINITE
Graph[i]->predcssor = NULL; //predecessor in the path set to NULL
}

I run gdb to debug my code. After I allocate memory and get into the second
for loop, for the second time, I find out that there is no member w of the
first struct, ie I write "print Graph[1]->w" and I get there is no member
named w (all this after I m in the loop for the second time, ie data are
entered in the Graph[2] struct. (I also tried Graph[i]= (Mode*)
malloc(sizeof (Node)) for those that didnt read the previous thread.

Please do be verbose in order to understand. Thank you in advance.
Nov 14 '05 #3
jimjim <fr*********@bl ueyonder.co.uk> writes:
for(i=1;i<=NUMV ERTEX;i++)
Graph[i]= malloc(sizeof (*Graph));
Hmm. Based on that code I wonder if I was really as clear as I
could have been. In fact, the proper use of sizeof in that case
would be
Graph[i]= malloc(sizeof (*Graph[i]));
where the innermost parentheses are optional.

Is MAX at least one greater than NUMVERTEX? C arrays run from 0
up to the dimension requested minus 1, so `int x[5];' declares an
array of 5 ints with indexes 0, 1, 2, 3, and 4.
for(i=1;i<=NUMV ERTEX;i++)
{
Graph[i]->v = i;
Graph[i]->known = NOTINTREE;
if(atoi(argv[2]) == i)
Graph[i]->dist = 0; //this is the source so set distance to zero
else
Graph[i]->dist = INFINITY; //distance from the source set to INFINITE
Graph[i]->predcssor = NULL; //predecessor in the path set to NULL
}
You could combine this loop with the previous one.
I run gdb to debug my code. After I allocate memory and get into the second
for loop, for the second time, I find out that there is no member w of the
first struct, ie I write "print Graph[1]->w" and I get there is no member
named w
I'm a little baffled why you expect a member named `w', because
your definition for `struct Node' didn't include a member named
`w'.
(all this after I m in the loop for the second time, ie data
are entered in the Graph[2] struct. (I also tried Graph[i]=
(Mode*) malloc(sizeof (Node)) for those that didnt read the
previous thread.


Hmm. Maybe I should have been more clear that sizeof (Node) is
correct, just not the best style.
--
char a[]="\n .CJacehknorstu" ;int putchar(int);in t main(void){unsi gned long b[]
={0x67dffdff,0x 9aa9aa6a,0xa77f fda9,0x7da6aa6a ,0xa67f6aaa,0xa a9aa9f6,0x1f6}, *p=
b,x,i=24;for(;p +=!*p;*p/=4)switch(x=*p& 3)case 0:{return 0;for(p--;i--;i--)case
2:{i++;if(1)bre ak;else default:continu e;if(0)case 1:putchar(a[i&15]);break;}}}
Nov 14 '05 #4
In article <news:h_******* **************@ news-text.cableinet. net>
jimjim <fr*********@bl ueyonder.co.uk> writes:
typedef in Vertex;
This is clearly not the code you compiled, because it contains a
typo (the word "in" should read "int"). That makes me suspect that
the rest of what you wrote is also not the code you compiled. As
such, the notes I make here are not necessarily the correct notes.
typedef struct Node{
Vertex v;
boolean known;
Distance dist;
Vertex predcssor;
}Node;

then in main() I ve got:
Node *Graph[MAX];
So far so good (modulo the typo). Note that valid values for
indexing the Graph[] array are 0 through MAX-1 inclusive. If
MAX is (say) 200, Graph[0] is OK, and Graph[199] is OK, but
Graph[200] is out of range.
and create structures dynamically:
for(i=1;i<=NUM VERTEX;i++)
Graph[i]= malloc(sizeof (*Graph));
Is NUMVERTEX different from MAX? If so, why? Note that Graph[0]
is not set here, and if NUMVERTEX is >= MAX, Graph[MAX] is used
when it does not exist. In general, in C, loops over arrays mostly
run "for (i = 0; i < N; i++)", not "for (i = 1; i <= N; i++)".

The call:

Graph[i] = malloc(sizeof (*Graph));

has the wrong general format. Calls to malloc should match the
pattern:

var = malloc(N * sizeof *var); /* or when N == 1: */
var = malloc(sizeof *var);

Here "var" is "Graph[i]" (and N is indeed 1), so this should be:

Graph[i] = malloc(sizeof *Graph[i])

(The parse order for the expression "*Graph[i]" is the same as that
for *(Graph[i]), so there is no need to parenthesize the variable
name Graph[i] in this case.)
for(i=1;i<=NUMV ERTEX;i++)
Again, this loop should probably run from 0 to MAX-1 (although your
algorithm probably depends on no node having index number 0). If
you prefer, you can have Graph[0] be deliberately unused, and change
the declaration to:

Node *Graph[NUMVERTEX + 1]; /* note: Graph[0] is never used */

(assuming NUMVERTEX is a constant).
{
Graph[i]->v = i;
Graph[i]->known = NOTINTREE;
Style comment: Graph[i]->known has type "Boolean" (which is presumably
just "int", unless you are using C99, in which case why not stick with
C99's "bool" in the first place?). "Proper" Boolean values are just
TRUE and FALSE; "NOTINTREE" is neither TRUE nor FALSE.
if(atoi(argv[2]) == i)
Graph[i]->dist = 0; //this is the source so set distance to zero
else
Graph[i]->dist = INFINITY; //distance from the source
set to INFINITE
Usenet-specific: Notice how the "//" comment text has changed, so
that the comment terminates at the word "source". The rest of the
comment has now become an (invalid) line of C code, which will draw
a diagnostic -- probably "syntax error" -- from the compiler. "//"
comments do not work well in code that may be reformatted by Usenet
News systems. "/*" comments do not suffer from this particular
problem.

Style-and-substance: atoi(argv[2]) has to "do work" to calculate
the "int" value of the series of digit characters in argv[2][0],
argv[2][1], argv[2][2], ..., up until argv[2][i] is '\0'. Unless
the compiler can prove to itself that atoi(argv[2]) returns the
same result on every trip through the loop, the compiler will have
to re-compute that value every time. It would make a lot more
sense to instruct the system to compute it once, and also give it
a name, e.g.:

int source_vertex;

if (argc < 3) {
... /* handle error, not enough arguments */
}
source_vertex = atoi(argv[2]);
/* now you can also check that source_vertex is a sensible number */
...
for (...) {
Graph[i]->v = i;
Graph[i]->known = FALSE; /* or whatever */
/* the source vertex is at distance 0; others are at INFINITY
until later calculation says otherwise */
Graph[i]->dist = i == source_vertex ? 0 : INFINITY;
Graph[i]->predcssor = NULL; //predecessor in the path set to NULL
}
According to the "struct Node" definition, the "predcssor" field
has type Vertex, which is an alias for "int" (assuming the typo
correction I made was the right one). NULL is not a suitable
value for "int"s, as it may -- at the C compiler's discretion --
be defined as ((void *)0).

If you are using the "Graph[0] is never used so that I can use
index 0 to mean no index" trick (as I suspect you are), and if
you really do mean to have the "predcssor" field contain the
index number of the predecessor (as opposed to, say, a value of
type "pointer to struct Node" pointing to the same place Graph[x]
would point to for predecessor node #x), just set it to 0.
If you *do* want predcssor to have type "struct Node *", give it
that type.
I run gdb to debug my code. After I allocate memory and get into the second
for loop, for the second time, I find out that there is no member w of the
first struct, ie I write "print Graph[1]->w" and I get there is no member
named w ...


There is indeed no member named "w". There are four members,
named "v", "known", "dist", and "predcssor" .
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #5
On Sat, 13 Dec 2003 09:29:49 GMT, jimjim
<fr*********@bl ueyonder.co.uk> wrote:

Ben Pfaff thank you very much for your comments. You were very clear and I
II follow your advice.

I now have a greater problem and have no idea whats wrong :-(
As I said I declare a structure:
typedef in Vertex;
typedef struct Node{
Vertex v;
boolean known;
Distance dist;
Vertex predcssor;
}Node;

then in main() I ve got:
Node *Graph[MAX];

and create structures dynamically:
for(i=1;i<=NUM VERTEX;i++)
Graph[i]= malloc(sizeof (*Graph));

for(i=1;i<=NUMV ERTEX;i++)
{
Graph[i]->v = i;
Graph[i]->known = NOTINTREE;
if(atoi(argv[2]) == i)
Graph[i]->dist = 0; //this is the source so set distance to zero
else
Graph[i]->dist = INFINITY; //distance from the source set to INFINITE
Graph[i]->predcssor = NULL; //predecessor in the path set to NULL
}

I run gdb to debug my code. After I allocate memory and get into the second
for loop, for the second time, I find out that there is no member w of the
first struct, ie I write "print Graph[1]->w" and I get there is no member
named w (all this after I m in the loop for the second time, ie data are
Where did you think the w was going to come from. Each Graph[i]
points to a Node (which is an alias for struct Node). This structure
has four members: v, known, dist, and predcssor. Not a w in sight.
entered in the Graph[2] struct. (I also tried Graph[i]= (Mode*)
malloc(sizeo f (Node)) for those that didnt read the previous thread.

Please do be verbose in order to understand. Thank you in advance.


<<Remove the del for email>>
Nov 14 '05 #6

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

Similar topics

21
3912
by: Matteo Settenvini | last post by:
Ok, I'm quite a newbie, so this question may appear silly. I'm using g++ 3.3.x. I had been taught that an array isn't a lot different from a pointer (in fact you can use the pointer arithmetics to "browse" it). So I expected that when I run this program, I get both c1.A and c2.A pointing to the same address, and changing c1.A means that also c2.A changes too. ----- BEGIN example CODE -----------
8
1952
by: michi | last post by:
Hello everybody, I have following problem: I have an array of pointers to structures: table* tab = new table; and structure table is like this: struct table{ CSLL::node* chain;
3
837
by: michi | last post by:
Hello, I need to initialize a 2 dimensional square arrays of structures. The size of array I get from the user. I can do one-dimensional array, but I don't know how to specify the size of array when I want to do it 2D. I want to do it using 'new' operator. Thanks, michi.
8
3672
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was static; if the input file contained more than entries, tough. This time I want to do it right - use a dynamic array that increases in size with each word read from the file. A few test programs that make use of **List and realloc( List, blah...
7
2470
by: Frank M. | last post by:
I'm trying to declare an array of pointers to structures so that I can make the last element a NULL pointer. I figure that it would more easily allow my library routines to know when to stop processing the array. typedef struct screen_disp { int sd_row; int sd_col; char *sd_buff; } SCR_DISP;
5
3118
by: Paminu | last post by:
Why make an array of pointers to structs, when it is possible to just make an array of structs? I have this struct: struct test { int a; int b;
7
2796
by: Kathy Tran | last post by:
Hi, Could you please help me how to declare an araay of pointer in C#. In my program I declared an structure public struct SEventQ { public uint uiUserData; public uint uiEvent; public uint uiParam0; public uint uiParam1;
15
3826
by: Paminu | last post by:
Still having a few problems with malloc and pointers. I have made a struct. Now I would like to make a pointer an array with 4 pointers to this struct. #include <stdlib.h> #include <stdio.h> typedef struct _tnode_t { void *content; struct _tnode_t *kids;
9
4255
by: Mr John FO Evans | last post by:
Am looking at adding structures to an embedded C emulator but am wondering what the standard is for copying structures(ie structa=structb) which contain pointers to memory and which are therefore not contiguous in memory. When such structures are copied what should C do with these elements? Or should copying be illegal in this case? John
0
7969
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
8272
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8381
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
8258
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...
1
5847
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3886
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...
0
3927
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2404
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
1
1494
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.