kosvidakis
kosvidakis

Reputation: 13

Converting integer to string with atoi/sprintf

This is not my whole code I just sum it up to be easy to see. I have no problem to convert the string into an integer but I cannot convert the integer into a string. The program just crashes. Here is the code. Look at the line with itoa.

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

#define SIZEX 49
#define SIZEY 6

int main() {
    size_t x, y;
    char *a[50][7];
    char name[50][100];
    char surname[50][100];
    char IN[50][100];
    char YOB[50][100];
    char usname[50][100];
    char pass[50][100];
    char totamount[50][100];

    for (x = 0; x <= SIZEX; x++) {         
        a[x][0] = name[x];
        a[x][1] = surname[x];
        a[x][2] = IN[x];
        a[x][3] = YOB[x];
        a[x][4] = usname[x];
        a[x][5] = totamount[x];
        a[x][6] = pass[x];
    }
    printf("\nPlease enter the name of the new user\n");
    scanf(" %s", a[0][0]);

    printf("Please enter the surname of the new user\n");
    scanf(" %s", a[0][1]);

    printf("Please enter the Identity Number of the new user\n");
    scanf(" %s", a[0][2]);

    printf("Please enter the year of birth of the new user\n");
    scanf(" %s", a[0][3]);

    printf("Please enter the username of the new user\n");
    scanf(" %s", a[0][4]);

    strcpy(a[0][6], a[0][4]);
    strrev(a[0][6]);

    a[0][5] = "0";

    int z;
    z = atoi(a[0][5]);
    z = z + strlen(a[0][4]) * 10;

    itoa(z, a[0][5], 10);
    //sprintf(a[0][5], "%d", z);

    printf("%s\n", a[0][5]);
    printf("%d\n", z);

    return 0;
}

Upvotes: 1

Views: 796

Answers (1)

Eugene Sh.
Eugene Sh.

Reputation: 18299

By doing this:

a[0][5]="0";

You are assigning to a[0][5] a pointer to a readonly memory containing string literal "0".

Here:

itoa( z, a[0][5],10 );

you are attempting to write there, giving you memory access violation.

Upvotes: 1

Related Questions