Issue with printing char *argv after a function call in C

int readOptions(char *argv[]){
        FILE * infile;
        char line_buf[BUFSIZ];
        int i = 0, j = 0 ; 
        infile = fopen("options","r");
            if(!infile){

                     fprintf(stderr,"File Read failure\n");
                        exit(2);
            }

        while( i < 10 && fgets(line_buf,sizeof(line_buf),infile)!=0){

             printf("Line buf : %s",line_buf); 
             argv[i] =  line_buf;                                   

             i++;                               
}

}

int main(){

int j ; 

char *options[10]; 

for(j = 0 ; j< 10 ; j++){

        options[j] = malloc(len * sizeof (char));
    } 

 readOptions(options);
for(j=0; j<10 ; j++)
         printf("%s %d\n",options[j], j );

}

The problem is that I always see - the program print only the last line read in the file. Where is the mistake ? and am I missing any important pointer concept with this code ?

Answers


Every element of argv points to the same line_buf. Use strdup() to create new strings instead (which you will later have to free).


Need Your Help

Enable the Show Formulas in Excel from C# code

c# excel excel-automation

I am creating a windows application in C# .net to open an excel sheet and edit it. I am using excel automation in c# to do this.After editing/modifying some values in the sheet I will save the entire

C Program that counts how many pass or fail grades and exits when a negative number is inputted

c loops do-while

I'm a newbie to C Programming and we're still starting on the loops. For our exercise today, we were tasked to create a do-while program that counts how many pass and fail grades there are but the ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.