wrong print in coding c using pointer and array without no warning - arrays

int main()
{
int i, Quant, *Qsize1[4];
char *size1[4], size[5];
for(i=0; i<3; i++)
{
printf("Select Size : (S, M, L, XL) ");
scanf("%s",size);
size1[i]=size;
printf("How much quantity for this size? : ");
scanf("%d",Quant);
Qsize1[i]=Quant;
}
for(i=0; i<3; i++)
{
printf("\nSize %s : %d",size1[i], Qsize1[i]);
}
return 0;
}
example of print that i want is = Size L : 25
but when i print the it will print the last size i enter.
also the quantity of that size is wrong.

All the sizes are the same when you print them because you're reading all of them to the same character array named size. Each iteration overrides the previous size, and then you end up with size1[0], size1[1], size1[2] all point to the last size.
Quantity is wrong because you should pass scanf the address of the integer: scanf("%d", &Quant);
Also, as mentioned in the comments, you should fix how you read size itself. See this question about how to do it properly.

Related

Reading and Printing a matrix

I tried to read and print a matrix using an external function (from another c file), the thing is that I want to read the matrix dimensions in the function and store them in the main function, how can I do this?
Do I need to return an array with the m and n dimensions of the matrix or can I access the variables that I created in main and change their value within the external function? (I prefer if someone would explain the second) I don't actually know how to use pointers and stuff.
Sorry for my English, I'm not a native speaker, also thanks for your response
The second and the third functions are in an external function.c file
int main(){
int num_of_rows, num_of_columns;
int matrix[10][10];
read_matrix(num_of_rows, num_of_columns, matrix);
print_matrix(num_of_rows, num_of_columns, matrix);
printf("\n Press any key to exit the program: ");
_getch();
return 0;
}
void read_matrix(int num_of_rows, int num_of_columns, int matrix[10][10]){
int i,j;
printf("\nPlease specify the number of rows:");
scanf("%d", &num_of_rows);
printf("\nPlease specify the number of columns: ");
scanf("%d", &num_of_columns);
printf("\nPlease introduce the matrix elements below:\n");
for(i=0; i<num_of_rows; i++){
for(j=0; j<num_of_columns; j++){
printf("matrix[%d][%d]= ", i, j);
scanf("%d", &matrix[i][j]);
}
}
}
void print_matrix(int num_of_rows, int num_of_columns, int matrix[10][10]){
int i,j;
for(i=0; i<num_of_rows; i++){
for(j=0; j<num_of_columns; j++){
printf("matrix[%d][%d]= %d", i, j, matrix[i][j]);
}
}
}
Parameters are passed by value in C.
In read_matrix, the num_of_rows parameter is a local variable. Even if you modify it, the caller won't see anything change. Same for num_of_columns.
You want this:
void read_matrix(int *num_of_rows, int *num_of_columns, int matrix[10][10]) {
// ^ add * ^ add *
...
scanf("%d", num_of_rows); // << remove the &
printf("\nPlease specify the number of columns: ");
scanf("%d", num_of_columns); // << remove the &
...
for (i = 0; i < *num_of_rows; i++) {
// ^add *
for (j = 0; j < *num_of_columns; j++) {
// ^add *
and in main:
read_matrix(&num_of_rows, &num_of_columns, matrix);
// ^ ^ add the &s
This is basic knowledge that is covered in your C learning material. Most likely in the chapter dealing with pointers and the one dealing with function calls.
Here's the catch. I tested your code and it works nicely. The problem is, what you want to achieve is only possible by using dynamic memory allocation. Take a look at the malloc and free functions.
You can read more about it on:
https://www.tutorialspoint.com/what-is-malloc-in-c-language
https://www.tutorialspoint.com/how-do-malloc-and-free-work-in-c-cplusplus
In C language you are responsible for allocation a space in memory for variable length data structures. Pointers just store an address to a specific memory space allocated to the desired data type.
e.g.:
int n, *p;
p = (int*) malloc(n * sizeof(int));
In this example, you are just giving p an address to the first integer from n integers you just allocated.
p will work just like a vector when using for loops because behind the scenes, it's exactly what happens when you traverse your fixed length vectors and matrices, but this time you were in control of it's length in runtime.
#include<stdio.h>
void main()
{
int x[3][3], p, q, max;
printf("Enter the elements of matrix: \n");
for(p=0;p<3;p++)
{
for(q=0;q<3;q++)
scanf("%d", &x[p][q]);
}
max=x[0][0];
printf("The matrix is as follows: \n");
for(p=0;p<3;p++)
{
for(q=0;q<=3;q++)
scanf(" %d", &x[p][q]);
}
for(p=0;p<3;p++)
{
for(q=0;q<3;q++)
{
if(x[p][q]>max)
max=x[p][q];
}
printf("\n");
}
printf("Maximum number in the matrix is: %d", max);
}
Output:
Enter the elements of matrix:
23 65 12
12 23 56
12 10 32
The matrix is as follows:
23 65 12
12 23 56
12 10 32
Maximum number in the matrix is: 65
Matrix Programs
Explore more matrix programs.

How to insert multiple elements in array in c program?

I can insert an element in an array but I want to know that is this possible to insert multiple(two or three..) element in an array by using c program. I tried a little, there is no problem or eror but it doesn't work.
Here is my code which I had tried to make a program which can insert multiple element in array:
#include<stdio.h>
int main(){
int size,i;
printf("Enter array length - ");
scanf("%d",&size);
int array[size];
printf("Enter array elements : \n");
for(i=0; i<size; i++){
scanf("%d",&array[i]);
}
int el_no; //el_no means elemnet no which user should input
printf("How many element you want to insert - ");
scanf("%d",&el_no);
int element[el_no];
printf("Element value - ");
for(i=0; i<el_no;i++){
scanf("%d",&element[i]);
}
int index[el_no];
printf("Index no - ");
for(i=0; i<el_no;i++){
scanf("%d",&index);
}
for(i=0; i<el_no;i++){
for(i=index[i]; i< size+el_no;i++){
array[i+1]=array[i];
}
}
for(i=0; i<el_no; i++){
array[index[i]]=element[i];
}
for(i=0; i<size+el_no; i++){
printf("%d\t",array[i]);
}
return 0;
}
You can't do what you want (at least, not directly). Once you say
int array[size];
that array can only hold size number of elements, no more.
Your program first stores values into array[0], array[1], ..., up to array[size-1]. That's perfectly fine.
But then when you say
for(i=0; i<el_no;i++){
for(i=index[i]; i< size+el_no;i++){
array[i+1]=array[i];
}
}
you are trying to move some of the array's elements over (to make room for new ones), but you're moving them outside the array, which is never going to work.
One fix (not quite what you want) would be to declare the array bigger than it needs to be. For example, you could say
int array[size+5];
and then later double-check that it will be big enough:
printf("How many element you want to insert - ");
scanf("%d",&el_no);
if(el_no > 5) {
printf("sorry, I can't insert that many\n");
exit(1);
}
The "better" way, although it gets into pointers and dynamic memory allocation perhaps sooner than you're ready to, would be to use a pointer simulating an array, using malloc to allocate space for it to point to:
int *array = malloc(size * sizeof(int));
Than, later, you can resize it:
array = realloc(array, (size + el_no) * sizeof(int));
This is just an example -- in reality, you'd need to check the return values of malloc and realloc to make sure they're not NULL, indicating that something has gone wrong.
Also there are some other problems with your code. The way you're using the auxiliary index array looks wrong, and probably isn't necessary at all.
As I tried to show in my comment, you're not specifying an index for the index array. In that loop, you're scanfing to &index, which is the wrong argument for scanf. Your compiler should be giving you a warning:
warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int (*)[el_no]' [-Wformat=]
32 | scanf("%d",&index);
| ~^ ~~~~~~
| | |
| | int (*)[el_no]
| int *
Despite the warning, what's most likely happening is each value you enter in the loop is getting stored at index[0]. You need to change that loop from
for(i=0; i<el_no;i++){
scanf("%d",&index);
}
to
for(i=0; i<el_no;i++){
scanf("%d",&index[i]); // <-- note the [i] addition
}
You've done this correctly in the previous loop
for(i=0; i<size; i++){
scanf("%d",&array[i]);
}
This may not be the only problem, but it's a problem, and too long for a comment.
I've edited the code and stated where to correct the faults
#include<stdio.h>
int main(){
Initialize j here
int size,i,j;
printf("Enter array length - ");
scanf("%d",&size);
int array[size];
printf("Enter array elements : \n");
for(i=0; i<size; i++){
scanf("%d",&array[i]);
}
int el_no; //el_no means elemnet no which user should input
printf("How many element you want to insert - ");
scanf("%d",&el_no);
int element[el_no];
printf("Element value - ");
for(i=0; i<el_no;i++){
scanf("%d",&element[i]);
}
int index[el_no];
printf("Index no - ");
here is a mistake you can correct
for(i=0; i<el_no;i++){
scanf("%d",&index[i]);//Add[i] here
}
Also do not use same variable in more than one for loop in a nested loop
for(i=0; i<el_no;i++){
for(j=index[i]; j< size+el_no;j++){//Use any other variable than 'i' in this for loop
depending on what you want to do you can correct this line below
array[i+1]=array[i];
}
}
for(i=0; i<el_no; i++){
array[index[i]]=element[i];
}
for(i=0; i<size+el_no; i++){
printf("%d\t",array[i]);
}
return 0;
}
All is good.
Hope you find it useful.

Why the output file isn't the same as the input of the variable?

I create it a program that asks for raw and columns after that asks you to put numbers to the dimensional array. This arrays inputs to a file. When i open the file i can't see the array.
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main () {
FILE *fp;
int n,m;
int i,j;
float b;
char filename[100];
int getfloat(float *);
printf("Number of rows\n");
scanf("%d",&n);
printf("Number of colums\n");
scanf("%d",&m);
float s[n][m];
for (i=1;i<=n;i++)
{
for (j=1;j<=m;++j)
{
printf("Insert number %d",i);
printf(",%d\n", j);
scanf("%f",&b);
s[i][j]=b;
}
}
printf("Enter file name \n");
scanf("%s", filename);
// ****print file****
fp=fopen(filename,"w+");
if(fp!=NULL)
{
fputs(s,fp);
fprintf("%c",s);
}
fclose(fp);
return 0;
the only thing i see is this
If you want a list of numbers, probably in some kind of grid in the file, then at the minimum you want a loop such as the following:
for (int i=0; i<n; ++i)
{
for (int j=0; j<m; ++j)
{
fprintf(fp, "%f ", s[i][j]);
}
fprintf(fp, "\n");
}
See fprintf for documentation on the format specifiers; you'll probably want to tweak that to get better-looking values.
Also, again, note that arrays start from 0. Your initial read loop skips the very first element, and writes past the end of the actual array.
fprintf("%c", s); and fputs does not print out the contents of the array, it prints out the location stored in the array's pointer and tries to interpret it as a char. What you would need to print out the proper values is to loop through each value and use fprintf with each float value, using s[i][j] similar to how you initialized it.
The way you initialized the array is also off, as arrays begin at 0, not 1. Currently your for loop does not ever access s[0][0] or s[1][0] and so on. Your for loops should have i initialized to 0, and have the condition be i < n instead of i<=n.

C program displays garbage value while taking user input using scanf

I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");

Segmentation fault in c dealing with scanf

I'm writing a program that requires me to do a union of two arrays. Here is my code so far.
I get Segmentation fault as an error after I enter set A.
#include <stdio.h>
void Union(int a[], int b[], int set1, int set2)
{
int u[20], i, j, unionIndex=0,trigger;
for(i=0; i<set1; i++)
{
u[unionIndex] = a[i];
unionIndex++;
}
for(i=0; i<set2; i++)
{
trigger=0;
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
{
trigger =1;
break;
}
}
if(trigger =0)
{
u[unionIndex]=b[i];
unionIndex++;
}
}
for(i=0;i<unionIndex;unionIndex++)
{
printf(" %d",u[i]);
}
}
int main(void) {
int N=0;
int M=0;
int i;
int j;
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
int a[N];
printf("Enter the numbers in set: ");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
printf("Please enter the number of elements in set B: ");
scanf("%d",M );
int b[M];
printf("Enter the numbers in set: ");
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
Union(a,b,N,M);
return 0;
}
I'm pretty sure the issue has something to do with arrays because the program will compile but i get the error right after the user enters set A. I'm a beginner at C but I know a lot more about Java, so I'm thinking this has something to do with memory allocation. I'm not really sure how to solve the issue, so if you could point me in the right direction that would be helpful.
You need to pass the address of the variable to scanf()
Change
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
to
printf("Please enter the number of elements in set A: ");
scanf("%d", &N);
Same goes for other place
printf("Please enter the number of elements in set B: ");
scanf("%d", &M);
There is another possible mistake
Its here
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
In this set1 is equal to N, so j will go from 0 to N-1. And array u[] has only 20 elements. There is a possibility of array access out of bound if some user enter value more then 20 for N.
The problem, as I see it is in
scanf("%d",N );
and
scanf("%d",M );
It invokes undefined behavior as scanf() needs the argument to a format specifier to be a pointer to the type.
Just to clarify, you're essentially passing the address as 0 (value of the variable), which is not a valid addres, anyway.
You need to pass the address there, like
scanf("%d", &N );
and
scanf("%d", &M );
That said, in your Union() function, you're using a user-defined value to limit the for loop, against a constant value 20. In case the user input is more than 20, you'll be overrunning the memory which invokes undefined behavior.
The reason you're getting the segmentation fault is because of how you're calling scanf when reading in N and M. The %d format specifier for scanf expects an int *, i.e. the address of an int, but you're passing in an int. This is undefined behavior.
So you can fix them like this:
scanf("%d",&N );
....
scanf("%d",&M );
Some addtional bugs:
When looping to read in the values for b:
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
You have the wrong loop indexes:
for(j=0;j<M;j++)
{
scanf("%d",&b[j]);
}
When checking trigger:
if(trigger =0)
This is an assignment, not a comparison:
if(trigger == 0)
When looping to print out u:
for(i=0;i<unionIndex;unionIndex++)
You're incrementing the wrong variable:
for(i=0;i<unionIndex;i++)
Finally, u need to have a length of at least set1 + set2, otherwise you risk writing off the end of the array:
int u[set1+set2];
Fix those and you should get the desired results.

Resources