kismacska1

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

void bban_gen(char*bban) {
char bankcode[5];
char prefix[7];
char number[11];
scanf("%s", bankcode);
scanf("%s", prefix);
scanf("%s", number);
bban = (char*) malloc(sizeof (char)*21);
strcpy(bban, bankcode);
bban += 4;
strcpy(bban, prefix);
bban += 6;
strcpy(bban, number);
bban -= 10;
printf("Bank code: %s\n", bankcode);
printf("Account prefix: %s\n", prefix);
printf("Account number: %s\n", number);
printf("BBAN: ");
int i, j;
for (i = 0; i < 20; i++) {
putchar(bban[i]);
if ((i + 1) % 4 == 0)
putchar(' ');
}
}

//tak dajak sa volala funkcia

int country_code(char *bban, char *country) {
int p1,p2;
p1=country[0]-'A'+10;
p2=country[1]-'A'+10;
return p1*100+p2;
}

int control_code(char *bban, int country){
char* control=(char*)malloc(sizeof(char)*27);
sprintf(control,"%s",bban);
control+=20;
sprintf(control,"%d",country);
control+=4;
sprintf(control,"00");
control-=24;
printf("%s\n",control);
}
int main(int argc, char** argv) {
char*bban;
bban_gen(bban);
printf("%d\n",country_code(bban,"CZ"));
control_code(bban,1235);
return (EXIT_SUCCESS);
}
You haven't said what the problem is, so I would normally ignore these. But the problems are pretty basic, so I'll try to help.

Let's look at main.
1
2
3
4
5
6
7
int main(int argc, char** argv) {
    char*bban;
    bban_gen(bban);
    printf("%d\n",country_code(bban,"CZ"));
    control_code(bban,1235);
    return (EXIT_SUCCESS);
}


Line 2: You create a string pointer that is uninitialised and to to be filled in in line 3
Line 3: You call bban_gen, but pass the parameter by value. So bban won't be filled in. You need to change the signature of bban_gen to:
 
void bban_gen(char** bban)

As bban points to memory allocated from the heap, it should be freed. Your code becomes:
1
2
3
4
5
6
7
8
9
10
int main(int argc, char** argv) {
    char*bban = NULL; // You should initialise this pointer to null
    bban_gen(&bban); // You need to fill in bban, so you must pass its address

    printf("%d\n",country_code(bban,"CZ"));
    control_code(bban,1235);

    free(bban); // Must free dynamic memory
    return (EXIT_SUCCESS);
}


Next, bban_gen. You snprintf to format your output, never use sprintf, or use strcat to concatenate strings.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void bban_gen(char** bban) {
    char bankcode[5];
    char prefix[7];
    char number[11];
    scanf("%s", bankcode);
    scanf("%s", prefix);
    scanf("%s", number);

    *bban = (char*) malloc(sizeof (char)*21);
    snprintf(bban, 21, "%s%s%s", bankcode, prefix, number);

    printf("Bank code: %s\n", bankcode);
    printf("Account prefix: %s\n", prefix);
    printf("Account number: %s\n", number);
    printf("BBAN: %s", *bban);
}


You can apply these fixes to control_code.
Last edited on
Topic archived. No new replies allowed.