#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;
}
Related
I want to create a program that can read scores from user and display the scores output in the form of stars. But it seems that my code keep getting an infinity loop. Can anyone tell me what is wrong with my looping.
#include <stdio.h>
int main() {
int i, k, j;
int score[5];
for(i = 1; i < 6; i++) {
printf("\nplease enter the score for %d match : ", i);
scanf("%d", &score[i]);
}
printf("\nstatistics collection points for 5 matches\n\n");
for (k = 1; k < 6; k++) {
printf("%d. ", k);
for (j = 1; j <= score[k]; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Array indices are 0 based in C. So for an array with 5 elements the indices are from 0-4 inclusive. You are using indices 1-5 which results in buffer overflow. Below is the corrected program with the for loops fixed up to use the right indices:
#include <stdio.h>
#define NUM_SCORES 5
int main()
{
int i, k, j;
int score[NUM_SCORES];
for(i = 0; i < NUM_SCORES ; i++)
{
printf("\nplease enter the score for %d match : ", i);
scanf("%d", &score[i]);
}
printf("\nstatistics collection points for 5 matches\n\n");
for (k = 0; k < NUM_SCORES ; k++){
printf("%d. ", k);
for(j = 1; j <= score[k]; j++){
printf("*");
}
printf("\n");
}
return 0;
}
You should also add a check to ensure scanf is able to successfully read each input.
I'm new to coding and new to C++. I am trying to write code in which one enters elements of the matrix. Afterwards, one column should be removed, and one row should be added. Removing one column works fine. However, after reallocating memory for the new number of rows, I get the message: segmentation fault (core dumped). I am using pointers to create and edit my matrix. Here is my code. Thanks for any help!
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c,r,**p,column,row;
printf("Enter the number of rows and columns:\n");
scanf("%d\n%d",&r,&c);
p=(int**)calloc(r,sizeof(int*));
if(p==NULL) printf("Memory not allocated.\n");
else{
for(int i=0;i<r;i++){
*(p+i)=(int*)calloc(c,sizeof(int));
printf("Enter %d. row\n",i+1);
for(int j=0;j<c;j++){
scanf("%d",*(p+i)+j);
}
}
printf("Original matrix:\n");
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
printf("%d ",*(*(p+i)+j));
}
printf("\n");
}
printf("Which column do you want to remove?");
scanf("%d",&column);
while(column<1||column>c){
printf("Wrong entry, enter again:");
scanf("%d",&column);
}
for(int i=0;i<=r-1;i++){
for(int j=column-1;j<=c-2;j++)
*(*(p+i)+j)=*(*(p+i)+j+1);
*(p+i)=(int*)realloc(*(p+i),(c-1)*sizeof(int));
}
printf("Matrix without %d. column:\n",column);
for(int i=0;i<r;i++){
for(int j=0;j<c-1;j++)
printf("%d ",*(*(p+i)+j));
printf("\n");
}
printf("Which row do you want to replace?\n");
scanf("%d",&row);
while(row<1||row>r){
printf("Wrong entry, enter again:\n");
scanf("%d",&row);
}
p=(int**)realloc(p,(r+1)*sizeof(int*));
if(p==NULL)
printf("Memory not allocated.\n");
else{
printf("Enter %d. row",row);
for(int i=r+1;i>row-1;i++){
*(p+i)=*(p+i-1);
}
for(int j=0;j<c-2;j++)
scanf("%d",*(p+row-1)+j);
printf("New matrix:\n");
for(int i=0;i<=r;i++){
for(int j=0;j<c-2;j++)
printf("%d ",*(*(p+i)+j));
printf("\n");
}
}
}
return 0;
}
When you realloc memory for p, you add one new row to that array (one additional pointer). But you never allocate the memory for that new row, and eventually you access this uninitialized pointer.
But that's not the real problem. In the loop where you want to bump the pointers up to make space for the inserted row, your initial value and loop increment are both wrong. With an initial value of int i=r+1, the first write to *(p+i) will access one past the allocated space (which would be p[0] thru p[r]). The loop increment should be a decrement, --i. Once this loop is done, then you can allocate space for the new row.
As other people here have stated, it is definitely easier to do this using std::vector.
However, I assume you are doing this as a learning exercise so I would definitely recommend you to finish this and understand where you went wrong. You were close, it looks like you just got confused with your indices. Try using more descriptive variable names and splitting stuff into functions to make it harder to get lost in your own code.
I modified your code to get it to do what i think you were trying to do. Take a look and let me know if that was helpful.
But yes, if you do any future C++ work, avoid doing C style malloc, alloc, free, etc... and consider working with the std libs.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c, r, ** p, column, row;
printf("Enter the number of rows and columns:\n");
scanf_s("%d\n%d", &r, &c);
p = (int**)calloc(r, sizeof(int*));
if (p == NULL) printf("Memory not allocated.\n");
else {
for (int i = 0; i < r; i++) {
*(p + i) = (int*)calloc(c, sizeof(int));
printf("Enter %d. row\n", i + 1);
for (int j = 0; j < c; j++) {
scanf_s("%d", *(p + i) + j);
}
}
printf("Original matrix:\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("%d ", *(*(p + i) + j));
}
printf("\n");
}
printf("Which column do you want to remove?");
scanf_s("%d", &column);
while (column<1 || column>c) {
printf("Wrong entry, enter again:");
scanf_s("%d", &column);
}
for (int i = 0; i <= r - 1; i++) {
for (int j = column - 1; j <= c - 2; j++)
* (*(p + i) + j) = *(*(p + i) + j + 1);
*(p + i) = (int*)realloc(*(p + i), (c - 1) * sizeof(int));
}
c -= 1;
printf("Matrix without %d. column:\n", column);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
printf("%d ", *(*(p + i) + j));
printf("\n");
}
printf("Which row do you want to replace?\n");
scanf_s("%d", &row);
while (row<1 || row>r) {
printf("Wrong entry, enter again:\n");
scanf_s("%d", &row);
}
p = (int**)realloc(p, (r + 1) * sizeof(int*));
if (p == NULL)
printf("Memory not allocated.\n");
else {
printf("Enter %d. row", row);
for (int i = 0; i < c; i++)
scanf_s("%d", *(p + row -1) + i);
printf("New matrix:\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
printf("%d ", *(*(p + i) + j));
printf("\n");
}
}
}
return 0;
}
I need to make some functions for 2-dimensional arrays (a.k.a. matrixes) and the problem just starts with the first one.
I allocated the matrix in the heap memory using malloc() and then I tried to make a function that initializes the matrixes using a for loop of scanf()s, but after 3 times it takes the input, the program crashes.
Here is the code I made
void initMatrix(int **mat,int row,int col)
{
for(int i=0;i<row;i++){
printf("\n");
for(int j=0;j<col;i++){
printf("Cell (%d,%d): ",i,j);
scanf("%d",&mat[i][j]);
}
}
}
int main()
{
int r,c;
printf("Number of rows: ");
scanf("%d",&r);
printf("Number of columns: ");
scanf("%d",&c);
int **arr = (int **)malloc(sizeof(int*) * r);
for(int i=0;i<r;i++)
arr[i]=(int*)malloc(sizeof(int) * c);
// int count=0;
// for (int i = 0; i < r; i++)
// for (int j = 0; j < c; j++)
// arr[i][j] = ++count;
for (int i = 0; i < r; i++){
printf("\n");
for (int j = 0; j < c; j++)
printf("%d ", arr[i][j]);
}
initMatrix(arr,r,c);
printf("\n");
free(arr);
}
If I manually insert the content of the matrix, the program does work (without the initmatrix() function), I don't know why… I probably made a mistake somewhere.
I first apologize if some of you find my problem stupid and easy to solve, but I am a very beginner in "c".
My task is to create an inverse of a 3x3 matrix using different functions.
What I am trying to do now is to tell the user to input values for the 3x3 matrix and then print them. I made 2 functions which read and print the values, but I have problems with calling them since I cannot directly call an array in printf.
For now I am able to run the program, enter the values and print a wrong result which leads to a not responding program.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 3 //defining the size of the matrix (3x3)
//prototyping the functions used to calculate the inverse of the matrix
void readMatrix(double a[SIZE][SIZE]);
void printMatrix(double a[SIZE][SIZE]);
main()
{
double a[SIZE][SIZE];
int i,j;
printf("Enter the values for the matrix:\n", i, j);
readMatrix(a);
printf("Your Matrix:%d\n",a[i][j]);
printMatrix(a);
return 0;
}
//function 1
//letting the user to enter a matrix
void readMatrix(double a[SIZE][SIZE]){
int i,j;
for(i = 0; i < SIZE; i++){
for(j = 0; j < SIZE; j++){
scanf("%d", &a[i][j]);
}
}
}
//function 2
//outputing the given matrix
void printMatrix(double a[SIZE][SIZE]){
int i,j;
for(i = 0; i < SIZE; i++){
for(i = 0; i < SIZE; j++){
printf("Your matrix is: %d", a[i][j]);
}
}
}
In printf and scanf, it is crucial that you pass the exact format specifier that matches the type of the pointer to the variable. If your format specifier doesn't match the supplied argument, the result is undefined behaviour.
In effect, this
scanf("%d", &a[i][j]);
Needs to be replaced with
scanf("%lf", &a[i][j]);
And the same for printf("Your matrix is: %d", a[i][j]); -> printf("Your matrix is: %lf", a[i][j]);
Also, in printMatrix, you've used the loop variable i in the inner loop twice. What you want is
for(i = 0; i < SIZE; i++){
for(j = 0; j < SIZE; j++){
printf("%lf ", a[i][j]);
printf("\n");
}
Edit: As pointed out by #cse in the comments, remove this line in main:
printf("Enter the values for the matrix:\n", i, j);
Since at this point, i, and j are not initialised, they'd contain junk.
in printMatrix, there is a infinite loop which will definitely lead your program to no responding. Should be:
for(j = 0; j < SIZE; j++){
printf("Your matrix is: %d", a[i][j]);
}
For printing the output: you will want to actually print out the entire thing rather than one value after another, correct?
printf ("matrix is:\n")
char outstr[64]; //arbitrary but plenty big enough
char * pout; //points to a point in the string
for(j = 0; j < SIZE; j++){
pout = outstr;
for(i = 0; i < SIZE; i++){
pout += sprintf (pout, "%lf," a [i][j]);
*(--pout) = 0; //end the string one char earlier (dangling ',')
printf ("[%s]\n", outstr);
}
Will print:
matrix is:
[1,2,3]
[4,5,6]
[7,8,9]
Where the numbers are of course the ones in the array.
Also unless you were intending on filling the matrix in a columnar fashion, you should switch the i and j loops on the input function. You are storing the matrix in memory transposed. (This code assumes that you are not)
There are following problems with above code:
In line printf("Your Matrix:%d\n",a[i][j]); of main() function, since variable i and j are not initialized so it contains garbage value. So don't print value at a[i][j] because it may cause of segmentation fault. OR initialize i and j with a valid value i.e. which is a valid index in array double a[][]. Also you can change line printf("Enter the values for the matrix:\n", i, j); in main() to printf("Enter the values for the matrix:\n");. Because i and j are not being used here.
In line scanf("%d", &a[i][j]); of function void readMatrix(double a[SIZE][SIZE]). Since you are reading a double primitive data type then you should use %lf formatter instead of %d. Same for line printf("Your matrix is: %d", a[i][j]) in function void printMatrix(double a[SIZE][SIZE]).
In line for(i = 0; i < SIZE; j++) of function void readMatrix(double a[SIZE][SIZE]). It should be for(j = 0; j < SIZE; j++) i.e. the variable to be used in inner loop should be j not i.
You can find working code here which is after correcting the code.
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;
}