Light
Light

Reputation: 25

Store input from user into an array

I'm writing a simple code in visual studio 2012 RC that asks the user to insert values for two-dimensional array.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROW 5
#define COL 3


int main()
{
    char array[ROW][COL];
    int value;

    for (int i = 0; i < ROW; i++)
    {
        for (int j = 0; j < COL; j++)
        {
            scanf("%d", &value);
            array[i][j] = value;
            // scanf("%d", &array[i][j]); //use this statement instead of  above 2 statements.
        }
        printf("\n");
    }

The problem is that the above code works fine; however, if I use (as pointed out in commented part)

scanf("%d", &array[i][j])

directly, instead of storing the input into a variable and then assigning it to the array, the program will give an error of something like 'stack memory around 'array' has corrupted'.

Could someone tell me why I'm getting this problem and how can I avoid it while storing the input directly into array, instead of storing the input in a variable first.

ps- This is my first post, so be gentle :)

Upvotes: 1

Views: 2541

Answers (3)

PhillipD
PhillipD

Reputation: 1817

@light:

btw, I tweaked the program and it turned out that if I use int array, there will be no problem. Still, I'd like to know why char array is giving the error?

If you want to use a char array, you can use the following.

At the moment I have only access to gcc, but when playing with your code I observed the following:

#define ROW 2   // note that I defined a 2x2 matrix
#define COL 2
....
char array[ROW][COL];
....
scanf("%c", &array[i][j]);
....

I use the following lines to print the result:

printf("\n");
for (int i = 0; i < ROW; i++)
{
    for (int j = 0; j < COL; j++)
    {
        printf("%c ", array[i][j]);
    }
    printf("\n");
 }

If I want the following four values as input 1 2 3 4 I observe the following:

$./a.out
1
2    # input breaks here and the following lines are printed....

1 

2 

However, if I use the following line

do {scanf("%c",&array[i][j]);} while ( getchar() != '\n' );

of code instead of

scanf("%d", &array[i][j]);

in your two for loops it seems to work as expected.

Example input and output (the numbers are actually chars):

$./a.out
1
2
3
4

1 2  #output 
3 4 

And of course it works for letters:

$./a.out
a
b
c
d

a b #output
c d

Upvotes: 0

Artur
Artur

Reputation: 7257

Declare your array as it should be declared:

int array[ROW][COL];

and this will solve your issue. %d format specifier expects pointer to int to be passed and you pass pointer to char. Your array is to small to fit values you try to put there with scanf.

Upvotes: 0

jlhonora
jlhonora

Reputation: 10699

Your'e trying to put an int (%d) into a char (char array[ROW][COL]), so there's a memory violation.

Upvotes: 1

Related Questions