0

If I have a char array in C I am using it in a loop:

char arr [100];
while (1) {
    fill arr from some source
    store arr in some where
}

Now, with this approach, I loose all the subsequent arrays, I maintain a pointer to the last one only. How can I maintain that?

Please don't suggest using strings to me :)

user1785771
  • 487
  • 2
  • 7
  • 18

3 Answers3

2

Use an alternate array to store previous strings:

char arr [100];
char* arrOfStrings[100];

int i = 0;
while (1) {
    //fill arr
    arrOfStrings[i] = malloc(strlen(arr)+1);
    strncpy(arrOfStrings[i], arr, strlen(arr));
    i++;
}
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

Use strcpy() to make copies.

char arr[100];
while(1) {
    /* fill arr */
    char *str = malloc(strlen(arr) + 1);
    strcpy(str, arr);
    /* store str in some where */
}
timrau
  • 22,578
  • 4
  • 51
  • 64
  • I don't see how this solves the problem that previous strings are lost. `str` is declared inside the loop, so outside of it it would be lost. See my answer. – Luchian Grigore Nov 06 '12 at 16:02
  • I made a typo and have fixed. It is `str` which should be stored somewhere, not `arr`. – timrau Nov 06 '12 at 16:03
  • 1
    -1 for teaching to cast the result of malloc in C. Read [this](http://c-faq.com/malloc/mallocnocast.html) and [this](http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc). – Lundin Nov 06 '12 at 16:17
0

I'd use linked lists, since you don't know the number of lines you want to store:

char arr[100];
struct listOfLines
{
    char *line;
    struct listOfLines *next;
};

struct listOfLines *myListOfLines = NULL;
struct listOfLines *tempLine = NULL;
while(1)
{
    /* Fill array from some source */
    myListOfLines = tempLine;
    tempLine = malloc(sizeof(struct listOfLines));
    tempLine->line = strdup(arr);
    tempLine->next = NULL;
}
Waterfrag
  • 517
  • 4
  • 20