Re: problem passing pointer array



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
.



Relevant Pages

  • Re: Pointers
    ... > pete wrote: ... especially the string functions, have pointers for parameters. ... char *strchr(const char *s, int c); ...
    (comp.lang.c)
  • Re: [ot]Re: system call in VC
    ... pete wrote: ... int main ... Any suggestions, hints, pointers etc etc is greatly appreciated. ...
    (comp.lang.c)
  • Re: Little help with free()
    ... pete escribió: ... Now I'm working in something with pointers, but it seems that I can't get it right. ... I have a int ** that I allocate with malloc, but when trying to free it I get an error. ... fn:Eligio Becerra Zavala ...
    (comp.lang.c)
  • Re: Promoting unsigned long int to long int
    ... pereges writes: ... It is 4 bytes i.e. same as unsigned long int. ... Keith Thompson kst-u@xxxxxxx ... Nokia ...
    (comp.lang.c)
  • Re: finding the median of a list without sorting
    ... pereges writes: ... int median(const intList * l) { ... of median makes the answer rational in some ... the linear solutions are rather fiddly ...
    (comp.programming)