A
arnuld
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 };
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;
arr[2] = s2;
/* 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
*/
print_twoelem( arr );
return 0;
}
void print_twoelem( struct two_elem* p )
{
printf("first element = %c, || %s\n", p->ch, p->word);
++p;
printf("second element = %c, || %s\n", p->ch, p->word);
}
===================== 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
[arnuld@dune C]$
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 };
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;
arr[2] = s2;
/* 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
*/
print_twoelem( arr );
return 0;
}
void print_twoelem( struct two_elem* p )
{
printf("first element = %c, || %s\n", p->ch, p->word);
++p;
printf("second element = %c, || %s\n", p->ch, p->word);
}
===================== 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
[arnuld@dune C]$