Write a program that reads strings(words) from a text file and copy the inverted words to another file (use the command line arguments).
Form a new array of words b from original array a using the function
void formNewArray(char **a, char **b, int n, char (t)(char *));

where n is the number of words in array, and t is the pointer to function for inverting a string.

The following program gives SIGSEGV segmentation fault in function formNewArray():

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

void form_temp_array(char **a,char **b,int n,char* (*t)(char *))
{
  int i;
  for(i=0 ;i<n; i++)
      strcpy(b[i],(*t)(a[i]));
}

char* reverseWord(char *word)
{
    char *new_word;
    new_word=strrev(word);
    return new_word;
}

void print(char **arr,int n)
{
  int i;
  for(i=0; i<n; i++)
      printf("%s\n",arr[i]);
}

int main()
{
   char* a[]={"PROGRAMMING","CODING"};
   int n=sizeof(a)/sizeof(char**);
   char* b[n];
   printf("original words:\n");
   print(a,n);
   printf("reversed words:\n");
   form_temp_array(a,b,n,&reverseWord);
   print(b,n);
   return 0;
}

Edited 11 Months Ago by negru

Here is the working code without file handling:

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

void form_temp_array(char **a,char **b,int n,char* (*t)(char *))
{
    int i;
    for(i=0 ;i<n; i++)
        b[i] = (*t)(a[i]);
}

char* reverseWord(char *word)
{
    char *new_word = strrev(word);    
    return new_word;
}

void print(char **arr,int n)
{
    int i;
    for(i=0; i<n; i++)
        printf("%s\n",arr[i]);
}

int main()
{
    int i;
    char* w[]={"PROGRAMMING","CODING"};
    int n = sizeof(w)/sizeof(char**);
    char* a[n];
    char* b[n];
    for(i = 0; i < n; i++){
        a[i] = malloc(strlen(w[i])+1);
        strcpy(a[i], w[i]);
    }
    printf("original words:\n");
    print(a,n);
    form_temp_array(a,b,n,reverseWord);
    printf("reversed words:\n");
    print(b,n);
    for(i = 0; i < n; i++)
        free(a[i]);
    return 0;
}

How to do file handling?

I see you figured out to not apply the & (address-of) modifire to reverseWord in the form_temp_array() call.

It depends upon whether the words in the input file are one word per line, or all on one or more lines. That will determine how you parse them (problem 'A'). As for writing the words to a new output file, simply open a file for write access and do an fprintf() with new-lines for each word if the input file had them one word per line, and without (until after all the input) in the case where the words were all in one line (problem 'B'). Since you don't provide an example of the input file, that's as good as I can give you.

This article has been dead for over six months. Start a new discussion instead.