Store a given amount of numbers using pointers in C - c

I'm trying to learn how to use pointers, and I'm trying to make a program that asks the user for a random number of integers they'd like to write in, and then printing them back to the user. Normally I'd use an array for this, but that defeats the whole purpose of learning pointers.
#include <stdio.h>
#include <malloc.h>
int main() {
int numberAmount = 0;
int *numbers;
printf("Type the amount of numbers you are going to write: ");
scanf("%i", &numberAmount);
numbers = (int*) malloc(sizeof(numberAmount));
if (numberAmount == 0) {
printf("No numbers were given");
}
else {
for (int i = 0; i < numberAmount; i++) {
scanf("%i", numbers);
}
while (*numbers != 0) {
printf("%i ", *numbers);
numbers++;
}
}
return 0;
}
This is what I've come up with so far, but it does not work.
Any ideas?

In this part of your code
for (int i = 0; i < numberAmount; i++) {
scanf("%i", numbers);
}
you're saving the number that the user inputted in the same memory location. So the value saved in the numbers pointer keeps changing whenever the user inputs a new integer instead of adding a new integer.
You can fix this by replacing scanf("%i", numbers); with scanf("%i", (numbers + i));. This way for every new input the user provides, it will be saved in the memory location next to numbers.

Related

Extreme sum values calculated inside a structure

While I was learning to code in C about structure and pointers, I tried to make a program that calculate grades of students.
I thought it would work from my previous experiences for such calculation without pointers and structure. But with those, it gave me wild results in the program.
#include <stdio.h>
#include <string.h>
/*
The program will scan year, name, score of three different subjects,
and calculate the sum and the average.
Three different people (using array) will be taken into account.
*/
struct grade {
int year;
char name[20];
int score[3];
int total;
float avg;
};
void main() {
struct grade p[3];
char str = 'c';
char *pstr = NULL;
int i, j;
pstr = &str;
for (j = 0; j < 3; j++) {
printf("Year of Admission: ");
scanf("%d", &p[j].year);
printf("Name of the Student: ");
scanf("%s", pstr);
strcpy(p[j].name, pstr);
for (i = 0; i < 3; i++) {
printf("The score for Subject %d: ", i + 1);
scanf("%d", &p[j].score[i]);
p[j].total += p[j].score[i];
}
p[j].avg = p[j].total / 3.0;
}
for (j = 0; j < 3; j++) {
printf("%s's\n", p[j].name);
printf("Total score: %d\n", p[j].total);
printf("Average: %.2f\n", p[j].avg);
}
}
I could have written each of three different subjects as one variable but for an extra "challenge", I made an array inside the structure.
int score[3];
However, the program only prints out extremely small number -89541694... for both totals and averages.
I assume that this particular line inside a for-loop is a problem.
scanf("%d", &p[j].score[i]);
But I could not figure out why. I am really new to pointers and still learning them.
I hope for your generous teaching and explanations.
Thank you in advance.
Local variables are not initialized with 0, so you just need to zero it before calculating total:
p[j].total = 0;
before
for (i = 0; i < 3; i++) {
printf("The score for Subject %d: ", i + 1);
scanf("%d", &p[j].score[i]);
p[j].total += p[j].score[i];
}
The variable pstr points to a single char. A string in C needs to be at least two characters for a single-character string: The actual character, and the null terminator.
When you use e.g. scanf to read a string, the function will write at least two bytes to the memory pointed to by pstr. But since it only points to a single byte you will write out of bounds and that leads to undefined behavior.
If you want to be able to read more than a single character you need to have more space allocated for the string. And you need to limit scanf so it will not write out of bounds.
For example
char pstr[40]; // Allows for strings up to 39 character, plus terminator
// ...
scanf("%39s", pstr); // Read at most 39 characters from standard input, and write to pstr
Another problem is that local variables are not automatically initialized, their values will be indeterminate.
That means the contents of the array p is unknown and seemingly random.
When you do
p[j].total += p[j].score[i];
you use the seemingly random value of p[j].total to calculate another seemingly random number.
To initialize all structures and all their members to "zero" in the array, do e.g.
struct grad p[3] = { 0 };
Instead of making pstr a pointer you might wanted to do somehting like this
char pstr[30];
And accordingly you will scanf the string using scanf("%29s",pstr); and check it's return value.
To describe the problem a bit - you had a pointer pointing to a char which is not capable of holding an input characters and the corresponding \0 (nul terminating character). As a result this gives rise to undefined behavior. And then using it in strcpy is also an illegal code. (Undefined behavior).
Here the solution I gave simply declared an array of 30 characters and we limited the string input using scanf upto 29 characters because we need to store the terminating null.
Showing you atleast a bit of code to make you understand how to write these codes:-
if( scanf("%29s",pstr)!= 1){
fprintf(stderrm"Error in input");
exit(EXIT_FAILURE);
}
Another problem is initialize the variables - here you used p[j].total += p[j].score[i]; What is the value of p[j].total initially. It contains garbage value. In the loop make p[j].total = 0; first. That will give you the correct result.
Note: The wild results are the garbage value resulted from addition of some garbage value with p[j].score[i].
Also note that without making the changes that I said if you only change the initialization thing then also code is not guranteed to work. undefined behavior is undefined behavior - cases may arise which will simply crash the program making you wonder where you went wrong.
Illustration code may help you:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
The program will scan year, name, score of three different subjects,
and calculate the sum and the average.
Three different people (using array) will be taken into account.
*/
struct grade {
int year;
char name[20];
int score[3];
int total;
float avg;
};
int main(void) {
struct grade p[3];
char pstr[20];
int i, j;
for (j = 0; j < 3; j++) {
printf("Year of Admission: ");
if(scanf("%d", &p[j].year)!=1){
fprintf(stderr, "%s\n", "Error in input");
exit(EXIT_FAILURE);
}
printf("Name of the Student: ");
if(scanf("%19s", pstr)!=1){
fprintf(stderr, "%s\n", "Error in input");
exit(EXIT_FAILURE);
}
strcpy(p[j].name, pstr);
p[j].total = 0;
for (i = 0; i < 3; i++) {
printf("The score for Subject %d: ", i + 1);
if(scanf("%d", &p[j].score[i])!=1){
fprintf(stderr, "%s\n", "Error in input");
exit(EXIT_FAILURE);
}
if(p[j].score < 0){
fprintf(stderr, "%s\n", "Error in input");
exit(EXIT_FAILURE);
}
p[j].total += p[j].score[i];
}
p[j].avg = p[j].total / 3.0;
}
for (j = 0; j < 3; j++) {
printf("%s's\n", p[j].name);
printf("Total score: %d\n", p[j].total);
printf("Average: %.2f\n", p[j].avg);
}
return 0;
}
In fact instead of using the pstr just input the names directly in the structure variable instance itself. No need to use a temporary variable.

Retaining input values in C?

I have asked for the user to enter in several values to calculate an average, however I'd like to also calculate a gradient which uses the inputted values. How do I name these values so I can use them again? Thank you.
Here is what I have thus far:
#include <stdio.h>
int main () {
int n, i;
float num[1000], total=0, mean;
printf("Enter the amount of x-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input x-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean=total/n;
printf("The mean of all the x-values entered is %.2f to 2 decimal places", mean);
{
float num[1000], total=0, mean;
printf("Enter the amount of y-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d",&n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input y-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean = total / n;
printf("The mean of all the y-values entered is %.2f to 2 decimal places", mean);
return 0;
}
}
Naming the variable is really up to you, but `int gradient[NUM_ELEMENTS]; seems appropriate. It is an array, which also seems appropriate if it's purpose is to assist in finding the gradient from a series of numbers.
Steps could be:
1) use printf to ask user for values, specify spaces or commas between values. You can also specify a limit of values. Example printf("enter 5 numbers separated by commas\n:");
2) use scanf or similar to read values from standard input (the terminal) into the array: scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
3) use the array an a function that will compute the gradient.
Simple example:
(where gradient computation, error checking, bounds checking etc. is all left to you)
int get_gradient(int a[5]);
int main(void) {
int gradient[5];
int iGradient=0;
printf("enter 5 numbers separated by commas");
scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
iGradient = get_gradient(gradient);
return 0;
}
int get_gradient(int a[5])
{
return [do computation here using array a];
}
Edit:
The above example works only if you know the number of elements at compile time. It uses an int array that has been created on the stack. If you do not know how big of an array you will need until run-time, for example if user input determines the size, then the array size needs to be determined at run-time. One options is to create the variable needed on the heap. (read about stack and heap here) The following uses some techniques different from the simpler version above to get user input, including a function I called get_int(), which uses scanf() in conjunction with strtol(). Here's the example:
int main(void) {
char input[80]={0};
char **dummy={0};
long *gradient = {0};
int iGradient=0;
int arraysize;
int i;
char* fmt = "%[^\n]%*c";
printf("how many numbers will be entered?");
scanf(fmt, input);
arraysize = strtol(input, dummy, 10);
gradient = calloc(arraysize, sizeof(long));
if(gradient)
{
for(i=0;i<arraysize;i++)
{
gradient[i] = get_int();
}
iGradient = get_gradient(gradient, arraysize);
//free gradient when done getting result
free(gradient);
}
return 0;
}
int get_gradient(int *a, int num)
{
int grad = 0, i;
//do something here to compute gradient
return grad;
}
long get_int(void)
{
char input[80]={0};
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}

Code blocks, adding and storing integers through a function

So I'm trying to get a simple program to work by asking the user to enter numbers within 1-100 and have the program store everything entered then tell the user later on all the numbers and how much it adds up to be.
Right now all I want to know is how do I store the variables and have the program be able to tell me how many numbers were entered.
Should I make a function outside of main that does the processing for storing and adding?
#include <stdio.h>
int main () {
int number, even, odd;
char name;
printf("Enter your name")
scanf(%d, &number);
scanf (%c, &char)
printf("Enter numbers within 1-100")
printf("Enter 0 to quit")
while (number != 0) {
if (number%2 == 1) {
//This is where I don't know how to store the odd numbers
}
else {
//And the even numbers here as well
}
}
printf("%c,the numbers you have entered are broken down as follows:\n",name);
printf("You entered %d even numbers with a total value of \n", even);
printf("You entered %d odd numbers with a total value of \n", odd);
return 0;
}
Here is a sample program. Enhance as required as suggested in the previous update.
#include <stdio.h>
#include <stdlib.h>
int
main ()
{
int number, even, odd;
int *evenarr, *oddarr;
int evencount = 0, oddcount = 0;
int i;
char name;
evenarr = (int *) malloc(100 * sizeof(int));
oddarr = (int *) malloc(100 * sizeof(int));
printf ("Enter numbers within 1-100");
printf ("Enter 0 to quit");
do
{
scanf ("%d", &number);
if (number != 0)
{
if (number < 1 || number > 100)
continue;
if (number % 2 == 1)
{
//This is where I don't know how to store the odd numbers
printf ("odd\n");
oddarr[oddcount] = number;
oddcount++;
/* Realloc the arr if size exceed 100 */
}
else
{
//And the even numbers here as well
printf ("even\n");
evenarr[evencount] = number;
evencount++;
/* Realloc the arr if size exceed 100 */
}
}
}
while (number != 0);
for(i=0; i<oddcount; i++)
printf("odd : %d\n", oddarr[i]);
for(i=0; i<evencount; i++)
printf("even : %d\n", evenarr[i]);
}
Your question is a little ambiguous but it seems to me that you may need to allocate memory dynamically for storage since you don't know how many numbers will be entered during run time.
This can be done multiple ways. The first method involves using the malloc() and realloc() functions. I'll leave you to research these functions but basically malloc() allocates memory on the heap during run time and realloc() allows you to resize the memory that was given to you.
I think the best method would be to implement a linked list data structure. This way you can store the numbers as the user enters them and then later iterate through the list and count how many numbers were odd or even. And similarly you can also calculate their totals.
More information on linked list data structures:
https://en.wikipedia.org/wiki/Linked_list
http://www.cprogramming.com/tutorial/c/lesson15.html
https://www.youtube.com/watch?v=vcQIFT79_50
These are just some of the resources I used to learn linked lists. There are plenty more information about linked lists on Google.
You can use malloc(). It allocates memory on the heap. Also, using realloc() allows you to resize the memory you allocated using malloc().
See this tutorial on malloc and free.
The code #Umamahesh has given is correct, just that he is not freeing the memory allocated by the program, which might be fatal.
So you just free the pointers. The corrected code in #Umamahesh answer is:
#include <stdio.h>
#include <stdlib.h>
int
main ()
{
int number, even, odd;
int *evenarr, *oddarr;
int evencount = 0, oddcount = 0;
int i;
char name;
evenarr = (int *) malloc(100 * sizeof(int));
oddarr = (int *) malloc(100 * sizeof(int));
printf ("Enter numbers within 1-100");
printf ("Enter 0 to quit");
do
{
scanf ("%d", &number);
if (number != 0)
{
if (number < 1 || number > 100)
continue;
if (number % 2 == 1)
{
//This is where I don't know how to store the odd numbers
printf ("odd\n");
oddarr[oddcount] = number;
oddcount++;
/* Realloc the arr if size exceed 100 */
}
else
{
//And the even numbers here as well
printf ("even\n");
evenarr[evencount] = number;
evencount++;
/* Realloc the arr if size exceed 100 */
}
}
}
while (number != 0);
for(i=0; i<oddcount; i++)
printf("odd : %d\n", oddarr[i]);
for(i=0; i<evencount; i++)
printf("even : %d\n", evenarr[i]);
free (evenarr);
free (oddarr);
}
Also see: How do free and malloc work in C?.

how to find array element from user input

friend i am new in c ,so i face problem in a ,code, plz if there is any wrong in my logic,take it as a pardon eye,
I am trying to find the element in a two dimensional array, so i have declare a two dimensional array in my code, i will take a user input, the input will compare with data in an full array a column index of two dimensional array, if any data found similar of that column index then it will give the same row data of another column of array. if i give a input in my code it is giving output of the number is not in array index, though the number is in the array index, so i dont understand where is my fault.
plz help me to fix the problem.
here is my code :
#include<stdio.h>
int main()
{
int arr[10][3]={{1,5},
{2,8},
{3,27},
{ 4,64},
{5,125},
{6,216},
{ 7,343},
{8,512},
{ 9,729},
{ 10,1000}};
int i, num;
printf("Enter a number\n");
scanf("%d",&num);
for(i=0;i<10;i++)
{
if (num==arr[i][0])
printf("%d",arr[i][1]);
break;
}
if (num==10)
printf("the number is not there");
return 0;
}
You have an errant semi-colon:
if (num==10);
printf("the number is not there");
That call to printf will run each time because there is no body for the if statement. With better formatting:
if (num==10);
printf("the number is not there");
As #zoska points out, you also have the same bug here:
if (num==arr[i][0]);
I would do the following three changes at the minimum:
Change int arr[10][3] to int arr[10][2]
Change
if (num==arr[i][0]);
printf("%d",arr[i][1]);
to
if (num == arr[i][0]) {
printf("%d",arr[i][1]);
}
Change
if (num==10);
printf("the number is not there");
to
if (i == 10) { // note: 'num' changed to 'i'
printf("the number is not there");
}
Your code should look like this in the future
#include <stdio.h>
int main(void)
{
int arr[10][2] = {
{1,5},
{2,8},
{3,27},
{4,64},
{5,125},
{6,216},
{7,343},
{8,512},
{9,729},
{10,1000}
};
int i, num;
printf("Enter a number\n");
scanf("%d", &num);
for(i = 0; i < 10; i++)
{
if (num==arr[i][0]) {
printf("%d", arr[i][1]);
break;
}
}
if (i == 10) {
printf("the number is not there");
}
return 0;
}

Need function to find largest value in an array, return it to main( ) and print out

To me, my program looks like it should do what I want it to do: prompt a user to enter 10 values for an array, then find the largest of those values in the array using a function, then return the largest number to the main () function and print it out.
But, when I enter values, I never get numbers back that look anything like the ones I'm entering.
For example, let's say I enter just "10, 11" I get back "1606416648 = largest value".
Does anyone know what I'm doing wrong?
Here's the code:
#include <stdio.h>
#define LIMIT 10
int largest(int pointer[]);
int main(void)
{
int str[LIMIT];
int max;
int i = 0;
printf("Please enter 10 integer values:\n");
while (i < LIMIT)
{
scanf("%d", &str[i]);
i++;
}
// Thanks for your help, I've been able to make the program work with the above edit!
max = largest(str);
printf("%d = largest value\n", max);
return 0;
}
int largest(int pointer[])
{
int i;
int max = pointer[0];
for (i = 1; i < LIMIT; i++)
{
if (max < pointer[i])
max = pointer[i];
}
return max;
}
scanf("%d", &str[LIMIT]); reads in one number and puts it in the memory location one past the end of your array.
After changes:
You don't need scanf() in your while condition; it should go in the while body instead.
Your scanf() still isn't quite right. You need to tell it where in the array you want to store the input.
str[i]; doesn't do anything.
printf("Please enter 10 integer values:\n");
scanf("%d", &str[LIMIT]);
This doesn't do what you think. First, it only reads one number in. Second, you are reading it into the last position + 1 of the array.

Resources