Can i use pointer in scanf to take input in an array? - c

I am trying to do this in c:
scanf("%d",a+i);
where a is an array of size 10. And i is counter for loop. So is this possible?

Absolutely: if a is an int* or an array int a[10], and i is between 0 and 9, this expression is valid.
The a+i expression is the pointer arithmetic equivalent of &a[i], which is also a valid expression to pass to scanf.

yes you can use a+i instead of &a[i],,,, The following code ask you to enter 10 numbers and will save them in an array,,,,and then displays the numbers in it.
check this code :
#include <stdio.h>
int main (void)
{
int a[10], i, j = 0;
for(i = 0; i < 10; ++i ){
printf("Element no %d = ",i);
scanf("%d",a+i);}
printf("Elements in your array are: ");
for(j = 0; j < 10; j++)
printf("%d ",a[j]);
return 0;
}
I hope if this code could help you !!

Try this solution:
#include <stdio.h>
int main (void)
{
int *p, i, j = 0, n;
printf("enter the value of n ");
scanf("%d",&n);
for(i = 0; i < n; ++i ){
scanf("%d",p+i);}
printf("Elements in your array are: ");
for(j = 0; j < 10; j++)
printf("%d ",*(p+i));
return 0;
}

Related

Same code works in main, but not when calling from a function in C

Okay so I'm a beginner programmer so any tips on any part of the code are greatly appreciated,
but the main question is why does the code in function int longestSequence(int n,int array[n]);work when placed in main, but not when called from the function?
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int longestSequence(int n,int array[n]);
int main()
{
int n;
scanf("%d", &n);
int mat[n][n];
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
scanf("%d", &mat[i][j]);
}
}
int arraySize = n*n;
int array[arraySize];
int arrayIndex = 0;
for(int i=0; i<n; i++){
if(i%2 == 0){
for(int j = 0; j<n; j++){
array[arrayIndex++] = mat[i][j];
}
}else{
for(int j = n-1; j>=0; j--){
array[arrayIndex++] = mat[i][j];
}
}
}
/// Here's the same code that works when in main
// int numOfSequental = 0;
// int maxNumOfSequental = INT_MIN;
// for(int i = 0; i<n; i++){
// if(niz[i] == (niz[i+1]-1)){
// numOfSequental++;
// if(numOfSequental>maxNumOfSequental){
// maxNumOfSequental = numOfSequental;
// }
// continue;
// }
// numOfSequental = 0;
// }
//calling the function in printf
printf("Length of the sequence: %d", longestSequence(arraySize, array[arraySize]));
return 0;
}
int longestSequence(int n,int array[n])
{
int numOfSequental = 0;
int maxNumOfSequental = INT_MIN;
for(int i = 0; i<n; i++){
if(array[i] == (array[i+1]-1)){
numOfSequental++;
if(numOfSequental>maxNumOfSequental){
maxNumOfSequental = numOfSequental;
}
continue;
}
numOfSequental = 0;
}
return maxNumOfSequental+1;
}
"the main question is why does the code in function int longestSequence(int n,int array[n]); work when placed in main, but not
when called from the function?"
As called it should not work in either place.
printf("Length of the sequence: %d", longestSequence(arraySize, array[arraySize]));
// ^^^^^^^^^^^
return 0;
Note first that the index passed: arraySize is one beyond the legal index for array. In C, indexing is zero based, and so it goes from 0 - arraySize - 1
More importantly though the 2nd argument of longestSequence should be a pointer to the array, not an indexed element of the array.
printf("Length of the sequence: %d", longestSequence(arraySize, array));
return 0;
Also, in general, to compare subsequent numbers in an array with size n, the range of comparisons should be limited to:
a[i] == a[i+1] //for i == 0 through i == n-1
Change:
for(int i = 0; i<n; i++){
// ^^^
if(array[i] == (array[i+1]-1)){//array out of bounds when i == n
// ^^^
To
for(int i = 0; i<n-1; i++){
// ^^^^^
if(array[i] == (array[i+1]-1)){//i will never reach n
EDIT:
One last thing addresses comment about replacing calls to scanf() with using the 2nd argument of main. First to do that the code must include the prototype of main: int main(int argc, char *argv[]);. With this prototype, the program as called from the command line can now include command line arguments, eg: if running from CMD prompt in Windows:
C:\dev> myProg.exe 3 1 2 3 4 5 6 7 8 9
Inside your program then arguments of argc and argv[]` are populated as follows:
argc == 11 //total number of arguments
argv[0] == "myProg.exe" //program name is alway in argv[0]
argv[1] == "3"
argv[2] == "1"
...
argv[10] == "9"
Which should translate to creating a 3x3 array populated with the 9 subsequent values.
So the first statements in your code could now be: (in psuedo code)
int n = atoi(argv[1]);//check value of n before using
int array[n][n];
int index = 2;
for(int i = 0; i<n ; i++)
for(int j = 0; j<n ; j++)
array[i][j] = atoi(argv[index]);
index++;

C program printing wrong output

I am trying to create a program which prints a matrix of integers, but the output returns weird numbers before the actual matrix. There are no compiling errors.
This is what my code looks like: //ignore void function for now, focus on main function::
#include <stdio.h>
#include <stdlib.h>
//array[30][30] = 2D array of max 30 rows and 30 columns
//n = number of rows and columns
void printmatrix(int array[30][30], int n){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%d", array[i][j]);
}
printf("\n");
}
return;
}
int main(){
int n;
scanf("%d", &n);
int ints2D[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
scanf("%d", &ints2D[i][j]);
}
}
printmatrix(ints2D, n);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%d ", ints2D[i][j]);
}
printf("\n");
}
return 0;
}
And this is my output (I only want the last three lines)
123
-514159984327663
-51415932632766-514159305
1 2 3
4 5 6
7 8 9
You are missing a space in "%d" in printmatrix, and, more importantly, it is not proper to pass an int [n][n] array for an int [30][30] parameter unless n is 30.
Change void printmatrix(int array[30][30], int n) to void printmatrix(int n, int array[n][n]), and change printmatrix(ints2D, n); to printmatrix(n, ints2D);. That makes the type of the argument you are passing match the type of the parameter.
In your function args you defined the array as fixed size ([30][30]) but you are passing a VLA ([3][3] in your example) which makes it find uninitialized memory and why you are seeing the strange numbers.
#Eric Postpischil answer is spot on. Another way to solve it: 2d arrays could be flatten into 1d. Here is a working code for you:
#include <stdio.h>
#include <stdlib.h>
//array[30][30] = 2D array of max 30 rows and 30 columns
//n = number of rows and columns
void printmatrix(int *array, int n){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%d ", array[i * n + j]);
}
printf("\n");
}
return;
}
int main(){
int n;
scanf("%d", &n);
int ints2D[n * n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
scanf("%d", &ints2D[i * n + j]);
}
}
printmatrix(ints2D, n);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%d ", ints2D[i * n + j]);
}
printf("\n");
}
return 0;
}

Couldn't get the reason for the fault in the code

This is a program to print the smallest value and its position in an array (defined by user).
#include <stdio.h>
int position_smallest(int a[],int n)
{
int smallest = a[0];
int i,k;
for(i=0; i<=n-1; i=i+1)
{
if(a[i]<a[0])
{
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main()
{
int n,j;
int a[n];
printf("Enter the size of the array: ");
scanf("%d", &n);
for(j=0; j<=n; j=j+1)
{
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
But upon running it, it shows following error:
Segmentation fault (core dumped)
What can be the possible reason(s) for it?
First error, as stated in one of the comments, is declaring an array of size n before even knowing how much n is.
Second mistake is for loop in your main function that goes from 0 to n, i.e. index of an array is out of bounds.
Try this:
int main() {
int n = 0, j = 0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
for (j = 0; j < n; j++) {
printf("a[%d] = ", j + 1);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
If this solved your problem, please mark it.
First of all:
int n, j;
both uninitialized. Initialize them otherwise you will get garbage values.
int n = 0, j = 0;
What happens if n by chance (very likely) is 0 in following line?
int a[n];
You allocate 0 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);
You will get segmentation fault in for() loop below because your loop is trying to put 10 elements where you allocated no memory at all.
What happens if uninitialized n by chance (very likely) is 2^32 * 4 bytes (ints max)?
int a[n];
You allocate 2^32 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);
You will not get segmentation fault but you will allocate 2^32 * 4 bytes of memory for your program and you will use only 10
Second if that is not enough:
for (j = 0; j <= n; ++j)
scanf("%d", arr[n];
will access 11th element of array which is undefined behavior, and you might even get segmentation fault there. As you know arrays in C arrays are indexed from 0 to n - 1 (if n is size of array).
Third your loop inside function:
for(i=0; i<=n-1; i=i+1)
is the same as:
for(i=0; i < n; ++i)
And finally, you have a bug in your code, I believe:
if(a[i]<a[0])
should be:
if (a[i] < smallest)
because it is most likely that you would like compare other number to already smallest element not to a[0]. Here is my code
#include <stdio.h>
int position_smallest(int a[],int n) {
int smallest = a[0];
int i = 0, k=0;
for(i=0; i<n; ++i) {
if(a[i]<smallest) {
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main() {
int n=0, j=0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
for(j=0; j<n; ++j) {
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
return 0;
}
The version above is legit for C99 and up standards. If you are using C89 and earlier compilers you are stack with fixed size as mentioned in #Saurabh's answer or preferably use malloc().
Here is malloc() version:
#include <stdio.h>
#include <stdlib.h>
int position_smallest(int a[],int n) {
int smallest = a[0];
int i=0,k=0;
for(i=0; i<=n-1; i=i+1) {
if(a[i]<smallest) {
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main() {
int n=0, j=0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int *a = malloc(sizeof(int) * n);
for(j=0; j<n; j=j+1) {
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
return 0;
}
Use this one:
#include <stdio.h>
int position_smallest(int a[],int n)
{
int smallest = a[0];
int i,k;
for(i=0; i<=n-1; i=i+1)
{
if(a[i]<a[0])
{
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main()
{
int n,j;
int a[100];
printf("Enter the size of the array: ");
scanf("%d", &n);
for(j=0; j<n; j=j+1)
{
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
Specify the size of the array anything but run the loop according to user's input.
And there is some problems in your function position_smallest. So if you want correct it then take a look at #Gox's answer.

Segmentation failure

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int score,i,j;
int *ptr, *ptr1;
int over;
printf("Enter the number of over");
scanf("%d",&over);
ptr=(int*)malloc(over*sizeof(int));
// do the iteration, outer for loop, read row by row...
for(i=0; i <= (over-1); i++)
{
printf("%d%d ", i, ptr[i]);
// inner for loop, for every row, read column by column and print the bar...
printf("Enter the number of run per over");
scanf("%d",&score);
ptr1=(int*)malloc(score*sizeof(int));
for(j = 1; j<= ptr1[i]; j++)
// print the 'bar', and repeat...
printf("|");
// go to new line for new row, and repeats...
printf("\n");
}
return 0;
}
You are using
ptr1=(int*)malloc(score*sizeof(int));
inside your for loop. That causes memory leak. You should free the memory.
You also have
printf("%d%d ", i, ptr[i]);
But ptr[i] has not been assigned any value, so it just gives garbage value. The same problem occurs in
for(j = 1; j<= ptr1[i]; j++)
So you need to assign some value to them before using them like this.
Casting the result of malloc doesn't make any sense, it is pointless and potentially bad practice.
printf("%d%d ", i, ptr[i]);. You print the value of an uninitialized memory cell. This is undefined behavior and might in theory cause the program to crash on some platforms. If you need the memory allocated to be initialized to zero, you should be using calloc() instead.
ptr1=(int*)malloc(score*sizeof(int)); for(j = 1; j<= ptr1[i]; j++) This code makes no sense whatsoever and will crash the program. You use ptr1 as if it was an initialied array of integers, while it is actually an uninitialized, single integer.
#include <stdio.h>
#include <stdlib.h>
int main(void){
int **scores;
int over, score;
int i, j;
printf("Enter the number of over : ");
scanf("%d", &over);
scores = (int**)malloc(over*sizeof(int*));
for(i = 0; i < over; i++){
printf("%d ", i + 1);
printf("Enter the number of run per over : ");
scanf("%d", &score);
scores[i] = (int*)malloc((score+1) * sizeof(int));// +1 for number of columns
scores[i][0] = score;
for(j = 1; j <= score; j++){
printf("%d Enter the score : ", j);
scanf("%d", &scores[i][j]);
}
}
for(i = 0; i < over; i++){
for(j = 1; j <= scores[i][0]; j++){
printf("|%d", scores[i][j]);
}
printf("|\n");
}
//deallocate
for(i = 0; i < over; i++)
free(scores[i]);
free(scores);
return 0;
}

How to initialize, create matrix and then print with using structure

I want to create 2D array using structure and read from user, then display it. But I can't find out what's wrong with this.
/Sorry guys.First, I want it to read a matrix elements from user, then I want to display whole matrix. But it doesn't print properly, it prints address of elements. Why is it printing address, not value? /
Here is my code:
#include <stdio.h>
struct Matrix {
int n,m;
int a[100][100];
}array;
int main() {
struct Matrix *p;
int i,j;
p = malloc(sizeof(array));
scanf("%d%d", &p->n, &p->m);
for (i = 0;i < p->n;i++)
for (j = 0;j < p->m;j++)
scanf("%d", p->a[i][j]);
for (i = 0;i < p->n;i++){
for (j = 0;j < p->m;j++)
printf("%d ", (p->a[i][j]));
printf("\n");
}
}
Change scanf("%d", p->a[i][j]); to scanf("%d", &p->a[i][j]);. Better to check the result of scanf() to ensure code received the expected data.
if (scanf("%d", &p->a[i][j]) != 1) Oops();
Enable all warning on your compiler. This problem popped up right away.
#include <stdio.h>
struct Matrix {
int n, m;
int a[100][100];
} array;
int main() {
struct Matrix *p;
int i, j;
p = malloc(sizeof(array));
scanf("%d%d", &p->n, &p->m);
for (i = 0; i < p->n; i++)
for (j = 0; j < p->m; j++) {
// scanf("%d", p->a[i][j]);
scanf("%d", &p->a[i][j]);
}
for (i = 0; i < p->n; i++) {
for (j = 0; j < p->m; j++)
printf("%d ", (p->a[i][j]));
printf("\n");
}
}

Resources