On 18 Nov, 08:06, arnuld <sunr...@invalid.addresswrote:
Quote:
I am passing an array of struct to a function to print its value. First
I am getting Segfaults and weired values. 2nd, is there any elegant way to
do this ?
>
/* Learning how to use an array of struct */
>
#include <stdio.h>
#include <stdlib.h>
>
enum { ARR_SIZE = 1 };
that's an unusual size for an array
Quote:
struct two_elem { char ch; char* word; };
>
void print_twoelem( struct two_elem*);
>
int main(void)
{
>
* struct two_elem arr[ARR_SIZE];
>
* char arr1[] = "ARNULD";
* char arr2[] = "UTTRE";
>
* struct two_elem s1;
* struct two_elem s2;
>
* s1.ch = 'a';
* s1.word = arr1;
* s2.ch = 'b';
* s2.word = arr2;
>
* arr[1] = s1;
oops. You accessed the second element of a single element array.
oops. You accessed the third element of a single element array.
C arrays start from zero
Quote:
* /* this is fine as we are passing a point to the first element which is struct
* * *two_ele and this is what exactly rquired by the function
* */
yes
Quote:
* print_twoelem( arr );
>
* return 0;
>
}
>
void print_twoelem( struct two_elem* p )
{
* printf("first element *= %c, || %s\n", p->ch, p->word);
you access the uninitialised 1st element
Quote:
* ++p;
* printf("second element = %c, || %s\n", p->ch, p->word);
you access the non-existent 2nd element
Quote:
>
}
>
===================== OUTPUT ==============================
[arnuld@dune C]$ gcc4 -ansi -pedantic -Wall -Wextra array-of-struct.c
[arnuld@dune C]$ ./a.out
first element *= n, || <-
second element = a, || ARNULD
Segmentation fault
quite
this is how I'd write it (some things are just different personnel
style)
************************************************** *************
#include <stdio.h>
#include <stdlib.h>
#define ARR_SIZE 2
#define ARRAY_SIZE(A) sizeof(A)/sizeof(*A)
typedef struct
{
char ch;
char* word;
} Two_elem;
void print_twoelem (const Two_elem p[], int n)
{
int i;
for (i = 0; i < n; i++)
printf ("first element = %c, || %s\n", p[i].ch, p[i].word);
}
int main (void)
{
Two_elem arr [ARR_SIZE];
char arr1[] = "ARNULD";
char arr2[] = "UTTRE";
Two_elem s1;
Two_elem s2;
s1.ch = 'a';
s1.word = arr1;
s2.ch = 'b';
s2.word = arr2;
arr [0] = s1;
arr [1] = s2;
print_twoelem (arr, ARRAY_SIZE (arr));
return 0;
}
--
Nick Keighley
"That's right!" shouted Vroomfondel "we demand rigidly defined
areas of doubt and uncertainty!"