Re: problem passing pointer array
- From: pete <pfiland@xxxxxxxxxxxxxx>
- Date: Mon, 30 Jun 2008 12:33:39 -0400
pereges wrote:
Hi, can some one please tell me why this program is not able to
function properly. I have a array a and i am trying to create a
pointer array b which points to elements less than 40 in a.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void create_ptr_list(int *a, int ***b, int n, int *size_ptr)
{
int i;
*size_ptr = 0;
for (i = 0; i < n; i++)
{
if (a[i] < 40)
(*size_ptr) ++;
}
*b = malloc(sizeof(int *) * (*size_ptr));
(*size_ptr) = 0;
for (i = 0; i < n; i++)
{
if (a[i] < 40)
(*b)[*size_ptr++]= &a[i];
}
}
int main(void)
{
int a[] = { 5, -6, 45, -100, 20, -150, 160, 40, 0, 0, 1};
int **b;
int size;
int i;
create_ptr_list(a, &b, 10, &size);
for(i = 0; i <size; i++)
printf("%d\n", *(b[i]));
return (0);
}
I would write that this way:
/* BEGIN new.c */
#include <stdio.h>
#include <stdlib.h>
int *create_ptr_list(int *a, size_t n, size_t *size_ptr)
{
int *b;
size_t i;
*size_ptr = 0;
for (i = 0; n > i; ++i) {
if (40 > a[i]) {
++*size_ptr;
}
}
b = malloc(*size_ptr * sizeof *b);
*size_ptr = 0;
if (b != NULL) {
for (i = 0; n > i; i++) {
if (40 > a[i]) {
b[(*size_ptr)++]= a[i];
}
}
}
return b;
}
int main(void)
{
int a[] = {5, -6, 45, -100, 20, -150, 160, 40, 0, 0, 1};
int *b;
size_t size;
size_t i;
b = create_ptr_list(a, 10, &size);
if (b != NULL) {
for (i = 0; size > i; ++i) {
printf("%d\n", b[i]);
}
} else {
puts("b == NULL");
}
free(b);
return 0;
}
/* END new.c */
The distinction between counters and sortable data
is more obvious with size_t counters.
I don't like to read sorting functions
where everything is int.
--
pete
.
- Follow-Ups:
- Re: problem passing pointer array
- From: pereges
- Re: problem passing pointer array
- References:
- problem passing pointer array
- From: pereges
- problem passing pointer array
- Prev by Date: Re: YAPL - Yet Another Programming Language
- Next by Date: Re: OOP
- Previous by thread: Re: problem passing pointer array
- Next by thread: Re: problem passing pointer array
- Index(es):
Relevant Pages
|