473,241 Members | 1,599 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

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 2820
jimjim <dt***@mdx.ac.uk> 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[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof 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<=NUMVERTEX;i++)
Graph[i]= malloc(sizeof (*Graph));

for(i=1;i<=NUMVERTEX;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*********@blueyonder.co.uk> writes:
for(i=1;i<=NUMVERTEX;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<=NUMVERTEX;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);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa6 7f6aaa,0xaa9aa9f6,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)break;else default:continue;if(0)case 1:putchar(a[i&15]);break;}}}
Nov 14 '05 #4
In article <news:h_*********************@news-text.cableinet.net>
jimjim <fr*********@blueyonder.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<=NUMVERTEX;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<=NUMVERTEX;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*********@blueyonder.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<=NUMVERTEX;i++)
Graph[i]= malloc(sizeof (*Graph));

for(i=1;i<=NUMVERTEX;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(sizeof (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
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...
8
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
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...
8
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...
7
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...
5
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
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...
15
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>...
9
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...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.