Question:
Could I possibly get some help with pointers to arrays in C?
nullpo
2010-12-07 01:42:01 UTC
So I'm working on a program in C that requires me to constantly alter the size and contents of an array I've created. My first thought was to create a pointer to an array and simply change what it points to to fit my needs, since arrays are immutable to the best of my knowledge.

Only problem is, I haven't the slightest clue how to go about creating pointers to arrays and such. There's probably some combination of free() and malloc() in there, but I'm not sure how to go about doing it exactly.
Six answers:
cja
2010-12-07 04:38:04 UTC
Yes, malloc/calloc and free are involved, but realloc is the function you're looking for. See my example below for a way to implement an array that can grow. It's nice to know how to do such things in C, but if you want to migrate to C++, its STL containers will provide these kinds of dynamic sizing features for free.



/*

  * import

  *

  * Accepts a set of numbers from standard input and stores in an array.

  *

  * Input may be redirected from a file, received through a pipe, or entered

  * interactively. If used interactively, input must be terminated with

  * ctrl-d after the final carriage return.

  *

  * Any number of numbers may be entered per line. Numbers may be separated

  * by any number and combination of spaces, commas, or tabs. Leading blanks

  * and blank lines are OK.

  *

  * Usage: ./import

  *

  */

#include

#include

#include



#define NUMSTR_LEN 256

#define WHITESPACE " ,\t"

#define MIN_ARRAY_LEN 10



typedef struct {

    int totalSize;

    int inUse;

    double *dArray;

} DoubleArray;



DoubleArray *new(int size);

void add(DoubleArray *, double);

int getSize(const DoubleArray * const); /* return total size of array */

int getLen(const DoubleArray * const); /* return number of array elements in use */

void print(DoubleArray *);

void delete(DoubleArray *);



int main(int argc, char *argv[]) {

      char numstr[NUMSTR_LEN], /* entered line */

                *s; /* pointer to next number in line */

      double n; /* value of entered number */

      DoubleArray *a = new(MIN_ARRAY_LEN);



      /* Read each number on each line entered, and add each to the array. */

      while ((s = fgets(numstr,NUMSTR_LEN,stdin)) != NULL) {

            while (s != (char *)NULL) {

                  s = &s[strspn(s,WHITESPACE)];

                  if (sscanf(s,"%lf",&n) == 1) add(a,n);

                  s = strpbrk(s,WHITESPACE);

            }

      }

      print(a);

      delete(a);

      exit(EXIT_SUCCESS);

}



DoubleArray *new(int size) {

    DoubleArray *a = calloc(1,sizeof(*a));

    a->dArray = calloc(size,sizeof(double));

    a->totalSize = size;

    a->inUse = 0;

    return a;

}



void add(DoubleArray *a, double val) {

    if (a->inUse == a->totalSize) {

        a->dArray = realloc(a->dArray,

                                      (a->totalSize += MIN_ARRAY_LEN) * sizeof(double));

    }

    a->dArray[a->inUse++] = val;

}



int getSize(const DoubleArray * const a) {

    return a->totalSize;

}



int getLen(const DoubleArray * const a) {

    return a->inUse;

}



void print(DoubleArray *a) {

    int i, len=getLen(a),size=getSize(a);

    printf("\nDoubleArray (%d of %d elements used):\n",len,size);

    for (i = 0; i < len; i++) {

        printf("\t%g\n",a->dArray[i]);

    }

}



void delete(DoubleArray *a) {

    free(a->dArray);

    free(a);

}



#if 0



Sample run:



$ ./import

1 2 3 4 5

6 7 8 9 10 11

12 13



DoubleArray (13 of 20 elements used):

                1

                2

                3

                4

                5

                6

                7

                8

                9

                10

                11

                12

                13



#endif
mkzx
2010-12-07 02:54:06 UTC
You can think of arrays *as* pointers in C. When you create an array:



int myArray[10];



myArray is a pointer to the first element of the array.



You could create your own pointer to this array:



int* myPtr;

myPtr = &myArray[0];



You can't increase the size of an array at runtime. If your array becomes too small, create a new one, double the size of the old one, and copy the contents from the first array into the second.



int myBiggerArray[20]

// copy in values from old array

myPtr = &myBiggerArray[0];



If the array is too big, no need to create a new smaller one - just make sure you remember which is the valid last element of the array.



Some C guru might know of a different way of doing this though...
tbshmkr
2010-12-07 04:27:36 UTC
Lots of help on line

=

A TUTORIAL ON POINTERS AND ARRAYS IN C

- http://home.netcom.com/~tjensen/ptr/pointers.htm

-

Arrays and Pointers

- http://www.lysator.liu.se/c/c-faq/c-2.html

-

C Programming/Pointers and arrays

- https://secure.wikimedia.org/wikibooks/en/wiki/C_Programming/Pointers_and_arrays
2017-01-17 09:48:31 UTC
hi, If u r making use of char guidelines then dont complication related to the dimensions of string, to be stored in that char pointer. Poiter reuires 2 bytes in ordinary terms. Char pointer holds in ordinary terms the address of the string no longer the string itself. so char *p; p="a"; or p="abcdefghijklmnopqrstuvwxyz"; so the two u save a character or a string of any length, doesnt count.
2010-12-07 02:40:51 UTC
try reading this thread here, http://www.daniweb.com/forums/post331005.html#post331005 specifically post 8 (2nd last post).
living_deadis420d
2010-12-07 01:48:41 UTC
ffirst off, are you using C++? C#? be more specific dude.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...