-3

I'm working on a project in C using layered architecture: App, UI, Domain, Repository and Controller modules. I'm beginner in C. I don't know how to pass strings as parameters from a function to another and finally write to a file. Simplified example:

UI.c:

#include "UI.h"
#include "Controller.h"
#include <string.h>

char* read_type(){
    static char type[51];
    printf("Type: ");
    scanf("%s",type);
    return type;
}


void manage_tasks(){
    char cmd;
    printf("Choose from options: ");
    scanf("%c",&cmd);
    if (cmd=='1') {
        char type[51];
        strcpy(type,read_type());
        add_control(type);
    }
}

Controller.c:

#include "Controller.h"
#include "Repository.h"
void add_control(char type[51]){
    add(id, day, money, &type[51]);
}

Repository.c:

#include "Repository.h"
#include <stdlib.h>
void add(char type[51]){
    FILE* f;
    f=fopen("locatie.....", "a");
    if (f==NULL) {
        perror("Error while opening the file! \n");
        exit(EXIT_FAILURE);
    }

    fprintf(f,"%s\n", type);
}

I know that every array is the address of the first element, but I did't understand exactly how functions work with string arrays.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
ABC
  • 537
  • 6
  • 17
  • This is unfortunately not very good program design. I'd recommend reading more about pointers, strings and dynamic memory allocation (in that order) before you write this program. – Lundin Mar 03 '15 at 15:54
  • Something to get started: http://www.tutorialspoint.com/cprogramming/c_strings.htm – R Sahu Mar 03 '15 at 15:57

2 Answers2

0

Use char * Controller.c:

#include "Controller.h"
#include "Repository.h"
void add_control(const char *s){
    add(id, day, money, s);
}

Repository.c:

#include "Repository.h"
#include <stdlib.h>
void add(const char *s){
    FILE* f;
    f=fopen("locatie.....", "a");
    if (f==NULL) {
        perror("Error while opening the file! \n");
        exit(EXIT_FAILURE);
    }

    fprintf(f,"%s\n", s);
}
Ôrel
  • 7,044
  • 3
  • 27
  • 46
-1

For the record, this has a quick-and-dirty fix. You're overthinking it: you don't need the & or the [51] when you're passing it around in Controller.c. Simply: add(id, day, money, type);

That said, other answerers are going to give you advice on how to properly clean up your code, how to properly use pointers, and how to avoid leaks. Those are the more preferrable solutions. Mine is the quick-and-dirty solution.

  • If you know you're posting a "quick-and-dirty solution" then you should not post it. Try explaining a little bit more instead of pointing to other's answers. – Telokis Mar 03 '15 at 16:13