1

Im writing a C code to read a file line by line which contains alphabets, CR,LF,'\0'. Below is my attached code sample. I want to store only alphabets from each line to an array such that the numbers of rows in the array equals no of lines in the file and column should be of varying length(depends on the number of character in i-th line).

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *buffer[100];
    char temp[128];
    int c,i=0,j=0;
    int pos=0;
    FILE *file;
    file = fopen("input", "r");
    if (file) {
        while ((c = getc(file)) != EOF){
            if ((c>=65 && c<=90) || (c>=97 && c<=122))
                temp[pos++]=c;
            else if(pos>1) {
                temp[pos]='\0';
                buffer[i]=temp;
                printf ("%s\n",temp);
                i++;
                pos=0;
            }
        }
    }
    fclose(file);
    while (j<i){
        printf("%s\n",buffer[j]);
        j++;
    }
}

If i run my above code, all my buffer[j] contains same string. Can anyone help me out in figuring what was wrong in the code.

1
  • 2
    A debugger would eagerly step up to the task if you asked it real nice. Apart from that, ask yourself "What am I storing in that pointer array each time I advance to a new string? Is it the same buffer address (temp) over and over?" Commented Apr 4, 2013 at 12:49

1 Answer 1

2

buffer[] is an array of pointers, in your while loop you are pointing each of them to your array temp[]

buffer[i]=temp; // assign the address of temp to buffer[i]

Then you're changing the content of your temp[] array, but the address is always the same.

If you want to store the data from temp into each position in buffer[] you need to allocate memory and copy the data over there. More like:

buffer[i]=malloc(strlen(temp) + 1);
strcpy(buffer[i], temp);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Or buffer[i] = strdup(temp) if you're feeling particularly POSIX-ish that morning =P. Nice answer.
@WhozCraig Even if you are feeling POSIX-ish, stick to standard C. There is no reason to ever use strdup anywhere.
@Lundin I'll keep that in mind. Someone must have some pull, because it wasn't part of the POSIX standard until POSIX.1-2001.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.