Re: problem passing pointer array
- From: pete <pfiland@xxxxxxxxxxxxxx>
- Date: Mon, 30 Jun 2008 13:30:23 -0400
pereges wrote:
On Jun 30, 9:33 pm, pete <pfil...@xxxxxxxxxxxxxx> wrote: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 */
I actually need an array of pointers.
Then, 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 */
--
pete
.
- References:
- problem passing pointer array
- From: pereges
- Re: problem passing pointer array
- From: pete
- Re: problem passing pointer array
- From: pereges
- problem passing pointer array
- Prev by Date: Re: OOP
- Next by Date: Re: OOP
- Previous by thread: Re: problem passing pointer array
- Next by thread: OOP
- Index(es):
Relevant Pages
|