473,763 Members | 4,584 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to assign memory dynamically to a array of structures

Hi everybody,

I am faceing problem while assigning the memory dynamically to a array
of structures .
Suppose I have a structure

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

I created array of structures in my program so that i can store the
data in array

hom_data arr[];

I want to know how to assign memory to this array of structure at
runtime.

Can anybody point waht is wrong with this code .
I able to compile it but its printing garbage values.

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

int main()
{
FILE *fout;

hom_data hom[30];---->how to allocate memory to this array of stuct
dynamically.
int i=0;

/* open input file and test to see if it is empty */
if ((fout = fopen("momtext. txt", "r")) == NULL) {
printf("error ---- file read is empty\n\n");
exit(1); }

/* open output file */
fout = fopen("momtext. txt", "r");
while (fscanf (fout ,"%08x %08x ", &hom[i].nod_de, &hom[i].hom_id)
!= 2)
{

fscanf(fout ,"%08x %08x", &hom[i].hom_type, &hom[i].hom_pid );
printf("%08x %08x ", hom[i].nod_de, hom[i].hom_id);
printf("%s %s %s\n", hom[i].hom_type, hom[i].hom_pid);
i++;

}
return 0;
}
Thanks in advance

Aug 11 '06 #1
11 3783
sk*******@gmail .com said:
Hi everybody,

I am faceing problem while assigning the memory dynamically to a array
of structures .
#include <stdlib.h>
#include <stdio.h>

struct T
{
int this;
int class;
int teaches;
int dynamic;
int memory;
int allocation;
};

int main(void)
{
size_t capacity = 32;
size_t count = 0;
char line[256] = {0};

/* allocate a bunch of structs to start off with */
struct T *p = malloc(capacity * sizeof *p);
if(p != NULL)
{
while(fgets(lin e, sizeof line, stdin) != NULL)
{
if(count >= capacity)
{
struct T *new = realloc(p, capacity * 2 * sizeof *new);
if(new != NULL)
{
p = new;
capacity *= 2;
}
else
{
/* take some kind of corrective action, or simply... */
fprintf(stderr,
"Couldn't allocate sufficient memory"
" for %lu items.\n",
(unsigned long)capacity * 2);
exit(EXIT_FAILU RE);
}
}
if(sscanf(line,
"%d %d %d %d %d %d",
&p[count].this,
&p[count].class,
&p[count].teaches,
&p[count].dynamic,
&p[count].memory,
&p[count].allocation) != 6)
{
fprintf(stderr,
"Input error on line %lu\n",
(unsigned long)count);
exit(EXIT_FAILU RE);
}
++count;
}

/* display sums in reverse order */
while(count-- 0)
{
int sum = p[count].this;
sum += p[count].class;
sum += p[count].teaches;
sum += p[count].dynamic;
sum += p[count].memory;
sum += p[count].allocation;
printf("%d\n", sum);
}

free(p);
}
else
{
fprintf(stderr, "Couldn't allocate memory\n");
}
return 0;
}

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Aug 11 '06 #2
sk*******@gmail .com writes:
I am faceing problem while assigning the memory dynamically to a array
of structures .
This look awfully familiar. Haven't you started several other threads
about this same problem? Why not just post a followup in the original
thread?
Suppose I have a structure

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;
Your struct tag "hom_id" is the same as the name of one of your struct
members. This is legal but confusing.

If you insist on using a typedef for your structure, and it doesn't
contain any pointers to the same type, you don't actually need the
tag:

typedef struct {
/* members */
} hom_data;

Or you can use the same identifier for the struct tag and the typedef:

typedef struct hom_data {
/* members */
} hom_data;

Personally, I'd drop the typedef and just refer to the type as "struct
hom_data", but a lot of people like typedefs for various reasons.
I created array of structures in my program so that i can store the
data in array

hom_data arr[];

I want to know how to assign memory to this array of structure at
runtime.

Can anybody point waht is wrong with this code .
I able to compile it but its printing garbage values.

#include <stdio.h>
#include <stdint.h>
#include <string.h>
Ok.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
These last 4 headers are not defined in standard C; they're
Unix-specific. If you actually used anything from them, I'd tell you
to try comp.unix.progr ammer. But as far as I can tell you're not, so
you can just delete them (at least in code you post here).
typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

int main()
Better:
int main(void)
{
FILE *fout;

hom_data hom[30];---->how to allocate memory to this array of stuct
dynamically.
int i=0;

/* open input file and test to see if it is empty */
if ((fout = fopen("momtext. txt", "r")) == NULL) {
printf("error ---- file read is empty\n\n");
exit(1); }
exit() is declared in <stdlib.h>; you need a #include for it. If your
compiler didn't warn you about that, turn up the warning level.

exit(1) is non-portable. Use exit(EXIT_FAILU RE).
>
/* open output file */
fout = fopen("momtext. txt", "r");
What? You just opened this file (and checked the result of fopen();
good for you). Now you open it again for reading, but your commment
says "open output file", and you don't check the result.

And why do you call it "fout" when it's used for input?
while (fscanf (fout ,"%08x %08x ", &hom[i].nod_de, &hom[i].hom_id)
!= 2)
{

fscanf(fout ,"%08x %08x", &hom[i].hom_type, &hom[i].hom_pid );
You checked the result of the first fscanf(), but not the second.
Always check the result of fscanf(). I think you're assuming there
will be no errors in your input file; that's a dangerous assumption.

Maybe you should use a single fcanf() to read all 4 value.

(I'd use fgets() followed by sscanf(); use fscanf() directly should
work, but it doesn't give you much flexibility in dealing with
errors.)
printf("%08x %08x ", hom[i].nod_de, hom[i].hom_id);
The "%08x" format for both fscanf() and printf() specifies an argument
of type unsigned int (or pointer to unsigned int for fscanf()).
You're using arguments of type int32_t, which may or may not be the
same type. <inttypes.hprov ides format specifiers for int32_t, but
it's unwieldy. For output, use "%08lx" and cast the arguments to
unsigned long. For input, you can read into temporaries of type
unsigned long and then assign to your uint32_t members.
printf("%s %s %s\n", hom[i].hom_type, hom[i].hom_pid);
You tell printf you're going to give it three char* arguments pointing
to strings, then you give it two int32_t arguments. Of course you're
getting garbage.
i++;

}
return 0;
}
Your real question was about how to dynamically allocate an array of
structures, when the number of structures you need is going to depend
on an input file (i.e., you don't know in advance).

You can either use malloc() to allocate an array, then use realloc()
to grow it as needed (and *always* check the value returned by both
functions), or you can use malloc() allocate one record at a time and
add each one to a linked list. (The latter isn't an array, which is
what you asked for, but it might suit your purposes. If not, you
could also build the linked list, then once you know how big it is you
can use a single malloc() to allocate an array and copy the linked
list elements into it. This does increase your memory requirements,
though.)

For a first draft, though, you might just declare a fixed-size array
and store values into it, keeping track of how many elements are being
used. This will fail if the input is too big, but it should be easier
to implement, and it will give you a chance to fix all the other
errors in your code before you start worrying about memory allocation.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 11 '06 #3
Hi there,
As per your suggestion i wrote this code .Here i am tring to copy each
line from the file into a structure .And passing it to a function which
creates a linked list and stores the values in it.

Now the problem is i am getting a segmentatin fault error , I think its
comming in the addnode_hom(); function.

-I am not able to rectify the problem .
->Is due to that i am tring to use same structure for creating a linked
list and passing the data to the function.

-I am tring but not getting the solution.

-can u help me
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct {
int32_t hom_node;
int32_t hom_id;
int32_t hom_rest;
int32_t hom_type;
struct hom_id *link;
}hom_data;

int addnode_hom (hom_data *homptr);
void printnode_data (hom_data *h_ptr);
int count(hom_data *h_ptr);

int main(void)
{
FILE *fp;
int count = 0;
int ret;
char buff[1024];
hom_data *homptr;
homptr = (struct hom_data *) malloc(sizeof(h om_data));
//printf("test_ma in1\n");
fp = popen("grep 0044 momtext.txt","r ");
//printf("test_ma in\n");
while(fgets(buf f,sizeof(buff), fp)!=NULL){
fscanf(fp,"%08x %08x %04x %08x",&homptr->hom_node,
&homptr->hom_id,
&homptr->hom_rest,
&homptr->hom_type);
ret = addnode_hom(hom ptr);
if(ret == 0)
{
printf("error\n ");
exit(1);
}
else {
/*printf("%08x %08x %04x %08x\n",homptr->hom_node,
homptr->hom_id,
homptr->hom_rest,
homptr->hom_type);*/
count++;
}
printf("%d\n",c ount);
free(homptr);
pclose(fp);
return 0;
}
}

void printnode_data (hom_data *h_ptr) {
//printf("test_pr int\n");
if(h_ptr == NULL){
printf("flie is empty ");

}
else{

printf("%08x %08x %04x %08x\n",h_ptr->hom_node,
h_ptr->hom_id,
h_ptr->hom_rest,
h_ptr->hom_rest,
h_ptr->hom_type);
printf ("\n");
}

}
int addnode_hom (hom_data * homptr){

hom_data *h_ptr,*current ,*new;
int ctr;
ctr=count(h_ptr );
if(ctr == 0){
h_ptr = (struct hom_data *) malloc (sizeof(hom_dat a));
if(h_ptr == NULL){
printf("error") ;}
memset(h_ptr, 0, sizeof(hom_data ));
//current = h_ptr;

h_ptr->hom_node = homptr->hom_node;
h_ptr->hom_id = homptr->hom_id;
h_ptr->hom_rest = homptr->hom_rest;
h_ptr->hom_type = homptr->hom_type;
h_ptr->link = NULL;
}
else{
current = (struct hom_data)malloc (sizeof(hom_dat a));
current = h_ptr;
while(current->link != NULL)
current=current->link;
}
new=(struct hom_data *)malloc(sizeof (hom_data));
memset(current, 0,sizeof(hom_da ta));
current->link=new;
new->hom_node = homptr->hom_node;
new->hom_id = homptr->hom_id;
new->hom_rest = homptr->hom_rest;
new->hom_type = homptr->hom_type;
new->link = NULL;
current=new;
printnode_data( current);

}

int count(hom_data *h_ptr)
{
int ctr=0;
while(h_ptr->link != NULL)
{
h_ptr = h_ptr->link;
ctr++;
}
return ctr;
}

Keith Thompson wrote:
sk*******@gmail .com writes:
I am faceing problem while assigning the memory dynamically to a array
of structures .

This look awfully familiar. Haven't you started several other threads
about this same problem? Why not just post a followup in the original
thread?
Suppose I have a structure

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

Your struct tag "hom_id" is the same as the name of one of your struct
members. This is legal but confusing.

If you insist on using a typedef for your structure, and it doesn't
contain any pointers to the same type, you don't actually need the
tag:

typedef struct {
/* members */
} hom_data;

Or you can use the same identifier for the struct tag and the typedef:

typedef struct hom_data {
/* members */
} hom_data;

Personally, I'd drop the typedef and just refer to the type as "struct
hom_data", but a lot of people like typedefs for various reasons.
I created array of structures in my program so that i can store the
data in array

hom_data arr[];

I want to know how to assign memory to this array of structure at
runtime.

Can anybody point waht is wrong with this code .
I able to compile it but its printing garbage values.

#include <stdio.h>
#include <stdint.h>
#include <string.h>

Ok.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

These last 4 headers are not defined in standard C; they're
Unix-specific. If you actually used anything from them, I'd tell you
to try comp.unix.progr ammer. But as far as I can tell you're not, so
you can just delete them (at least in code you post here).
typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

int main()

Better:
int main(void)
{
FILE *fout;

hom_data hom[30];---->how to allocate memory to this array of stuct
dynamically.
int i=0;

/* open input file and test to see if it is empty */
if ((fout = fopen("momtext. txt", "r")) == NULL) {
printf("error ---- file read is empty\n\n");
exit(1); }

exit() is declared in <stdlib.h>; you need a #include for it. If your
compiler didn't warn you about that, turn up the warning level.

exit(1) is non-portable. Use exit(EXIT_FAILU RE).

/* open output file */
fout = fopen("momtext. txt", "r");

What? You just opened this file (and checked the result of fopen();
good for you). Now you open it again for reading, but your commment
says "open output file", and you don't check the result.

And why do you call it "fout" when it's used for input?
while (fscanf (fout ,"%08x %08x ", &hom[i].nod_de, &hom[i].hom_id)
!= 2)
{

fscanf(fout ,"%08x %08x", &hom[i].hom_type, &hom[i].hom_pid );

You checked the result of the first fscanf(), but not the second.
Always check the result of fscanf(). I think you're assuming there
will be no errors in your input file; that's a dangerous assumption.

Maybe you should use a single fcanf() to read all 4 value.

(I'd use fgets() followed by sscanf(); use fscanf() directly should
work, but it doesn't give you much flexibility in dealing with
errors.)
printf("%08x %08x ", hom[i].nod_de, hom[i].hom_id);

The "%08x" format for both fscanf() and printf() specifies an argument
of type unsigned int (or pointer to unsigned int for fscanf()).
You're using arguments of type int32_t, which may or may not be the
same type. <inttypes.hprov ides format specifiers for int32_t, but
it's unwieldy. For output, use "%08lx" and cast the arguments to
unsigned long. For input, you can read into temporaries of type
unsigned long and then assign to your uint32_t members.
printf("%s %s %s\n", hom[i].hom_type, hom[i].hom_pid);

You tell printf you're going to give it three char* arguments pointing
to strings, then you give it two int32_t arguments. Of course you're
getting garbage.
i++;

}
return 0;
}

Your real question was about how to dynamically allocate an array of
structures, when the number of structures you need is going to depend
on an input file (i.e., you don't know in advance).

You can either use malloc() to allocate an array, then use realloc()
to grow it as needed (and *always* check the value returned by both
functions), or you can use malloc() allocate one record at a time and
add each one to a linked list. (The latter isn't an array, which is
what you asked for, but it might suit your purposes. If not, you
could also build the linked list, then once you know how big it is you
can use a single malloc() to allocate an array and copy the linked
list elements into it. This does increase your memory requirements,
though.)

For a first draft, though, you might just declare a fixed-size array
and store values into it, keeping track of how many elements are being
used. This will fail if the input is too big, but it should be easier
to implement, and it will give you a chance to fix all the other
errors in your code before you start worrying about memory allocation.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 14 '06 #4
sk*******@gmail .com wrote:
>
Hi there,
As per your suggestion i wrote this code .Here i am tring to copy each
line from the file into a structure .
And passing it to a function which
creates a linked list and stores the values in it.
Here's a program that shows one way how to do that:

/* BEGIN line_to_string. c */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>

struct list_node {
struct list_node *next;
void *data;
};

int line_to_string( FILE *fp, char **line, size_t *size);
void list_free(struc t list_node *node, void (*free_data)(vo id *));
void list_fprint(FIL E *stream, struct list_node *node);
struct list_node *string_node(st ruct list_node **head,
struct list_node *tail,
char *data);

int main(void)
{
struct list_node *head, *tail;
int rc;
char *buff_ptr;
size_t buff_size;
long unsigned line_count;

puts(
"\nThis program makes and prints a list of all the lines\n"
"of text entered from the standard input stream.\n"
"Just hit the Enter key to end,\n"
"or enter any line of characters to continue."
);
tail = head = NULL;
line_count = 0;
buff_size = 0;
buff_ptr = NULL;
while ((rc = line_to_string( stdin, &buff_ptr, &buff_size)) 1) {
++line_count;
tail = string_node(&he ad, tail, buff_ptr);
if (tail == NULL) {
break;
}
puts(
"\nJust hit the Enter key to end,\n"
"or enter any other line of characters to continue."
);
}
switch (rc) {
case EOF:
if (buff_ptr != NULL && strlen(buff_ptr ) 0) {
puts("rc equals EOF\nThe string in buff_ptr is:");
puts(buff_ptr);
++line_count;
tail = string_node(&he ad, tail, buff_ptr);
}
break;
case 0:
puts("realloc returned a null pointer value");
if (buff_size 1) {
puts("rc equals 0\nThe string in buff_ptr is:");
puts(buff_ptr);
++line_count;
tail = string_node(&he ad, tail, buff_ptr);
}
break;
default:
break;
}
if (line_count != 0 && tail == NULL) {
puts("Node allocation failed.");
puts("The last line entered didnt't make it onto the list:");
puts(buff_ptr);
}
free(buff_ptr);
puts("\nThe line buffer has been freed.\n");
printf("%lu lines of text were entered.\n", line_count);
puts("They are:\n");
list_fprint(std out, head);
list_free(head, free);
puts("\nThe list has been freed.\n");
return 0;
}

int line_to_string( FILE *fp, char **line, size_t *size)
{
int rc;
void *p;
size_t count;

count = 0;
while ((rc = getc(fp)) != EOF) {
++count;
if (count + 2 *size) {
p = realloc(*line, count + 2);
if (p == NULL) {
if (*size count) {
(*line)[count] = '\0';
(*line)[count - 1] = (char)rc;
} else {
ungetc(rc, fp);
}
count = 0;
break;
}
*line = p;
*size = count + 2;
}
if (rc == '\n') {
(*line)[count - 1] = '\0';
break;
}
(*line)[count - 1] = (char)rc;
}
if (rc != EOF) {
rc = count INT_MAX ? INT_MAX : count;
} else {
if (*size count) {
(*line)[count] = '\0';
}
}
return rc;
}

void list_free(struc t list_node *node, void (*free_data)(vo id *))
{
struct list_node *next_node;

while (node != NULL) {
next_node = node -next;
free_data(node -data);
free(node);
node = next_node;
}
}

void list_fprint(FIL E *stream, struct list_node *node)
{
while (node != NULL) {
fputs(node -data, stream);
putc('\n', stream);
node = node -next;
}
}

struct list_node *string_node(st ruct list_node **head,
struct list_node *tail,
char *data)
{
struct list_node *node;

node = malloc(sizeof *node);
if (node != NULL) {
node -next = NULL;
node -data = malloc(strlen(d ata) + 1);
if (node -data != NULL) {
if (*head == NULL) {
*head = node;
} else {
tail -next = node;
}
strcpy(node -data, data);
} else {
free(node);
node = NULL;
}
}
return node;
}

/* END line_to_string. c */
--
pete
Aug 14 '06 #5
pete wrote:
while ((rc = line_to_string( stdin, &buff_ptr, &buff_size)) 1) {
rc is either EOF or the number of bytes in the resulting string.
The above line of code was written to terminate the loop
when the length of the string is zero, in other words,
when there is one byte in the string.
You probably would want to chage the condition to

while ((rc = line_to_string( stdin, &buff_ptr, &buff_size)) 0) {

for use with an ordinary text file.

--
pete
Aug 14 '06 #6

pete wrote:
pete wrote:
while ((rc = line_to_string( stdin, &buff_ptr, &buff_size)) 1) {

rc is either EOF or the number of bytes in the resulting string.
The above line of code was written to terminate the loop
when the length of the string is zero, in other words,
when there is one byte in the string.
You probably would want to chage the condition to

while ((rc = line_to_string( stdin, &buff_ptr, &buff_size)) 0) {

for use with an ordinary text file.

--
pete
Thanks for the code .But there is one more think i have to ask

I am getting this error while compiling the program,which i have
written .Can any body just tell why I am getting this .
tet.c: In function `addnode_hom':
tet.c:78: parse error before `else'
tet.c: At top level:
tet.c:92: parse error before `}'
Tcode is
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>

struct data{
int32_t hom_id;
int32_t hom_rest;
struct data *link;
}*hom_data;

void addnode_hom (int32_t *hom_id,int32_t *hom_rest);
void printnode_data ();
//int count(hom_data *h_ptr);

int main(void)
{
FILE *fp;
int count = 0;
int32_t hom_node;
int32_t hom_id;
int32_t hom_rest;
int32_t hom_type;
char buff[1024];
//hom_data *homptr;
//homptr = (struct hom_data *) malloc(sizeof(h om_data));
//printf("test_ma in1\n");

fp = popen("grep 0044 momtext.txt","r ");
//printf("test_ma in\n");
while(fgets(buf f,sizeof(buff), fp)!=NULL){
fscanf(fp,"%08x %08x %04x %08x",&hom_node ,
&hom_id,
&hom_rest,
&hom_type);
addnode_hom((in t32_t*)hom_id,( int32_t*)hom_re st);

count++;
}
printf("%d\n",c ount);
// free(hom_data);
// pclose(fp);
return 0;
}

void printnode_data () {
struct data *current;
current = hom_data;

while(current->link!=NULL)
{
printf(" %08x %04x \n",hom_data->hom_id,
hom_data->hom_rest);
}
}
void addnode_hom (int32_t *hom_id , int32_t *hom_rest)
{
struct data *current,*new;
new = (struct data *)malloc(sizeof (struct data));
if ( hom_data == NULL)
{
hom_data = (struct data *)malloc(sizeof (struct data));
//memset(hom_data , 0, sizeof(struct data));
current = hom_data;
else{
current = hom_data;
while (current->link!=NULL)
{
current=current->link;
}
}
current = (struct data *)malloc(sizeof (struct data));
current->link=new;

current->hom_id = hom_data->hom_id;
current->hom_rest = hom_data->hom_rest;
//new->link=NULL;
}
}

Aug 14 '06 #7
sk*******@gmail .com wrote:

<snip>
I am getting this error while compiling the program,which i have
written .Can any body just tell why I am getting this .
tet.c: In function `addnode_hom':
tet.c:78: parse error before `else'
So perhaps you should look at line 78 and above?
tet.c: At top level:
tet.c:92: parse error before `}'
<snip>
if ( hom_data == NULL)
{
hom_data = (struct data *)malloc(sizeof (struct data));
//memset(hom_data , 0, sizeof(struct data));
current = hom_data;
else{
<snip>

If you actually indented your code even vaguely sensibly, i.e. increased
the indentation level as you go in to blocks, the problem would be
obvious. People indent for a reason!

if ( hom_data == NULL)
{
hom_data = (struct data *)malloc(sizeof (struct data));
//memset(hom_data , 0, sizeof(struct data));
current = hom_data;
else {

The above is reindented more sensibly. You should now be able to see the
problem.

Indentation is a style issue, but I don't know anyone who would not
consider yours terrible.

Also, I'm sure someone must have told you about not casting the return
value of malloc. If not, read the FAQ and search the group for far
better ways to use malloc.
--
Flash Gordon
Still sigless on this computer.
Aug 14 '06 #8
Sorry but I am not able to understand what u intented to tell me.
Flash Gordon wrote:
sk*******@gmail .com wrote:

<snip>
I am getting this error while compiling the program,which i have
written .Can any body just tell why I am getting this .
tet.c: In function `addnode_hom':
tet.c:78: parse error before `else'

So perhaps you should look at line 78 and above?
tet.c: At top level:
tet.c:92: parse error before `}'

<snip>
if ( hom_data == NULL)
{
hom_data = (struct data *)malloc(sizeof (struct data));
//memset(hom_data , 0, sizeof(struct data));
current = hom_data;
else{

<snip>

If you actually indented your code even vaguely sensibly, i.e. increased
the indentation level as you go in to blocks, the problem would be
obvious. People indent for a reason!

if ( hom_data == NULL)
{
hom_data = (struct data *)malloc(sizeof (struct data));
//memset(hom_data , 0, sizeof(struct data));
current = hom_data;
else {

The above is reindented more sensibly. You should now be able to see the
problem.

Indentation is a style issue, but I don't know anyone who would not
consider yours terrible.

Also, I'm sure someone must have told you about not casting the return
value of malloc. If not, read the FAQ and search the group for far
better ways to use malloc.
--
Flash Gordon
Still sigless on this computer.
Aug 14 '06 #9
On Mon, 14 Aug 2006 03:30:32 UTC, sk*******@gmail .com wrote:
Hi there,
As per your suggestion i wrote this code .Here i am tring to copy each
line from the file into a structure .And passing it to a function which
creates a linked list and stores the values in it.

Now the problem is i am getting a segmentatin fault error , I think its
comming in the addnode_hom(); function.

-I am not able to rectify the problem .
->Is due to that i am tring to use same structure for creating a linked
list and passing the data to the function.

-I am tring but not getting the solution.

-can u help me
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct {
int32_t hom_node;
int32_t hom_id;
int32_t hom_rest;
int32_t hom_type;
struct hom_id *link;
}hom_data;

int addnode_hom (hom_data *homptr);
void printnode_data (hom_data *h_ptr);
int count(hom_data *h_ptr);

int main(void)
{
FILE *fp;
int count = 0;
int ret;
char buff[1024];
hom_data *homptr;
homptr = (struct hom_data *) malloc(sizeof(h om_data));
How often should we tell you:

NEVER EVER ccast the result of malloc(). It will hide some errors and
may send you in the lands of undefined behavior.

casts are the most dangerous featers of C. Never use a cast - ecxept
you knows exactly what you does, and even then check and recheck if
the cast is really needed. And thereafter, when you means you needs a
cast you mostenly wrong again.

Never use a cast because the compiler comlains! Be sure you understund
really what the compiler will tell you. Mostenly he does NOT tell you
you should use a cast. It will tell you that you have done a mistake
but seldom you has to cast something. So check again what you've done
and fix it without a cast. Cast only, really only when you're really
and absolutely sure that you really and absolutely knows what you are
doing and why the cast is really neccessary.
//printf("test_ma in1\n");
fp = popen("grep 0044 momtext.txt","r ");
//printf("test_ma in\n");
while(fgets(buf f,sizeof(buff), fp)!=NULL){
fscanf(fp,"%08x %08x %04x %08x",&homptr->hom_node,
&homptr->hom_id,
&homptr->hom_rest,
&homptr->hom_type);
You've forgotten tho test the result of fscanf.
ret = addnode_hom(hom ptr);
if(ret == 0)
{
printf("error\n ");
exit(1);
}
else {
/*printf("%08x %08x %04x %08x\n",homptr->hom_node,
homptr->hom_id,
homptr->hom_rest,
homptr->hom_type);*/
count++;
}
printf("%d\n",c ount);
free(homptr);
pclose(fp);
return 0;
}
}

void printnode_data (hom_data *h_ptr) {
//printf("test_pr int\n");
if(h_ptr == NULL){
printf("flie is empty ");

}
else{

printf("%08x %08x %04x %08x\n",h_ptr->hom_node,
h_ptr->hom_id,
h_ptr->hom_rest,
h_ptr->hom_rest,
h_ptr->hom_type);
printf ("\n");
}

}
int addnode_hom (hom_data * homptr){

hom_data *h_ptr,*current ,*new;
int ctr;
ctr=count(h_ptr );
if(ctr == 0){
h_ptr = (struct hom_data *) malloc (sizeof(hom_dat a));
if(h_ptr == NULL){
same as above.
printf("error") ;}
memset(h_ptr, 0, sizeof(hom_data ));
memset is mostenly leading to undefined behavior. Setting an array of
bytes to 0 is no guarantee to get pointers, ints and other nonbyte
values set to propper value but will result in trap representations .
So aboid memset for structs and other non byte values to avoid
failtures.
//current = h_ptr;

h_ptr->hom_node = homptr->hom_node;
h_ptr->hom_id = homptr->hom_id;
h_ptr->hom_rest = homptr->hom_rest;
h_ptr->hom_type = homptr->hom_type;
h_ptr->link = NULL;
}
else{
current = (struct hom_data)malloc (sizeof(hom_dat a));
See above.
current = h_ptr;
while(current->link != NULL)
current=current->link;
}
new=(struct hom_data *)malloc(sizeof (hom_data));
memset(current, 0,sizeof(hom_da ta));
current->link=new;
new->hom_node = homptr->hom_node;
new->hom_id = homptr->hom_id;
new->hom_rest = homptr->hom_rest;
new->hom_type = homptr->hom_type;
new->link = NULL;
current=new;
printnode_data( current);

}

int count(hom_data *h_ptr)
{
int ctr=0;
while(h_ptr->link != NULL)
{
h_ptr = h_ptr->link;
ctr++;
}
return ctr;
}

Your indents makes it impossible to identify the block levels, making
it too hard to understund what the logic of your program is.

At lest: DON'T TOPPOPST. Remove anything you have no comment for. Use
clean indent.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Aug 14 '06 #10

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

Similar topics

2
5345
by: hall | last post by:
I have a question regarding where memory is allocated when arrays are created. I'll illustrate this by example. I may be wrong on some details, do feel free to correct me. The code piece: int p; Creates a 2dimensional array. p can be thought of as a pointer, containing the adres of the first element in the array. The memory is
5
1640
by: slurper | last post by:
when i do this vector < vector<int> > p; later in the code i do things like this: vector<int> x,y,z; p.push_back(x); p.push_back(y); p.push_back(z);
8
4483
by: Berk Birand | last post by:
Hi all, I have to use C-style structures for an assignement. I cannot have any methods or constructors for it. What has surprised me is that in my code, I have to allocate memory for an array of structures with malloc. Otherwise, I get a seg fault. Here's the code: struct Employee { char* name; // Pointer to character string holding name of employee. int salary;
5
1906
by: mikegw | last post by:
Hello all. I am currently using an implementation of sysV shared memory. The entire shared memory is allocated is one continuous block of which I get the pointer to the head, everything should be done as offsets from this. At the moment I have two data structures, a head to a linked list which in it contains the pointer to the first element in the linked list( this is redundant as far as I can work out) and the list itself. The data...
5
3760
by: swarsa | last post by:
Hi All, I realize this is not a Palm OS development forum, however, even though my question is about a Palm C program I'm writing, I believe the topics are relevant here. This is because I believe the problem centers around my handling of strings, arrays, pointers and dynamic memory allocation. Here is the problem I'm trying to solve: I want to fill a list box with a list of Project Names from a database (in Palm this is more...
94
4765
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring that I found inside of a string. Any ideas?
3
2559
by: Jinkuzo | last post by:
Have been working on this project for a week, unfortunately missed the lesson on it and have been struggling to figure it out. These are the instructions and the point at which I'm up to. So essentially we don't know the size of the array and the user doesn't specify size, it's all done on the fly. Point I'm up to:
3
6676
by: Amit_Basnak | last post by:
Dear Friends I have the follwoing function "tss_fe_get_own_info" which has the arguments as shows below tss_fe_get_own_info(char *user_id, tss_user_profile_t **p_buf_UserSecInfo, error_status_t *retStatus) // Structure tss_user_profile_t from the function typedef struct {
7
1931
by: pereges | last post by:
I've to store an array of structures: typedef struct { double origin; double e_field_at_origin_real, e_field_at_origin_imag; double direction; double pathlength; int depth; }ray;
0
9386
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
10144
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
9997
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
8821
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
5270
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
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
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
3
3522
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2793
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.