Click to See Complete Forum and Search --> : c problem
Ok, I have a structure with an array of ints in it.
struct structure
{ int array [5];
}
How do i point to a single int within the array inside the structure.
ptr->array[number]
Doesn't work. It seg faults during run.
TIA.
EscapeCharacter
10-26-2001, 10:42 AM
what does the rest of the code look like?
TheLinuxDuck
10-26-2001, 10:55 AM
Hena:
Make sure that if you're using a pointer to the struct that you first allocate memory for the struct:
#include <stdio.h>
#include <stdlib.h>
//
struct my_struct {
int array[5];
};
//
int main(void)
{
struct my_struct *ints;
ints=(struct my_struct *)malloc(sizeof(struct my_struct));
if(ints==NULL) {
perror("ints: allocation error");
return 1;
}
ints->array[0]=10;
printf("0: %d\n", ints->array[0]);
free(ints);
return 0;
}
[ 26 October 2001: Message edited by: TheLinuxDuck ]
pinoy
10-26-2001, 06:18 PM
How do i point to a single int within the array inside the structure.
struct structure s;
int *p = s.array;
*p = 5;
printf("%d\n", s.array[0]);
s.array[0] = 10;
printf("%d\n", *p);
Hmm... i think my pointer seems to be working fine, but the when compared empty place (where the pointer points) to number it seg faults. Thanks for the help to find that out. As far as my program goes I think it has something to do with the putting the numbers to array. Back to the drawing board.
[ 29 October 2001: Message edited by: Hena ]
Right. I got the error it was in the linked lists link that was failing, as well as one other error in there. But thanks for showing that my pointers wasn't failing :).
[ 29 October 2001: Message edited by: Hena ]