954,190 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

simple structure question

#include <stdio.h>

struct FUN {
	char x;
	char *y;
	int z[20];
};

int main(void) {

	struct FUN fn1;
	struct FUN fn2;
	struct FUN fn3[10];
	struct FUN fn4[50];

return 0;
}

is an assignment like fn4[23] = fn3[5] invalid?

degamer106
Junior Poster
131 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 
#include <stdio.h>

struct FUN {
    char x;
    char *y;
    int z[20];
};

int main(void) {

    struct FUN fn1;
    struct FUN fn2;
    struct FUN fn3[10];
    struct FUN fn4[50];

return 0;
}

is an assignment like fn4[23] = fn3[5] invalid?


What happened when you tried it? ;)

Set up a function to move the parts of FUN from one value to another.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,492 posts since May 2006
Reputation Points: 3,348
Solved Threads: 943
 

> is an assignment like fn4[23] = fn3[5] invalid?
Well it's fine as far as the syntax is concerned.

However, the pointer inside the structure presents big problems.

fn1.y = malloc( 10 * sizeof *fn1.y );
fn2 = fn1;
free( fn1.y );
// fn2.y is now a dangling pointer.


Structure assignments in C know nothing about the internals of the struct, it's just a handy wrapper around memmove( &fn2, &fn1, sizeof fn2 );

In C++, we would use a proper copy constructor to replicate what the pointer pointed to rather than just making a copy of the pointer.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

structures can be copied directly into each other but copying array as such leads to error. In such cases copy the structures using pointers to the strutures.

himanjim
Junior Poster in Training
67 posts since Jul 2006
Reputation Points: 14
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You