Just getting to learn C better and I'm playing with arrays.
I would like to enter my phone number into an array like this:
#include <stdio.h>
int main()
{
int phoneNum[10];
for (int i = 0; i < sizeof(phoneNum); i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
return 0;
}
This seems to fail as it keeps asking me for a new digit. So I tried to print the size of the array:
int phoneNum[10];
printf("%lu", sizeof(phoneNum));
which incredibly gives me the result of 40 even though I initialized it to be 10 (?).
I have three questions:
Why is the result 40 and not 10 in sizeof(phoneNum) ?
How can I add elements in an array successfully with scanf in the above manner?
If the above manner is silly, is there a better, more efficient way to do this? For example directly enter 10 digits into an array? I can of course use scanf("%d%d%d...", digit1, digit2, digit3, ...) but I would like a generalized way, using the size of the array (say I don't know it and it's passed from another function)
sizeof(phoneNum) returns 10 * sizeof(int). The sizeof(int) value appears to be 4 for your system.
#include <stdio.h>
int main()
{
int phoneNum[10] = {0};
const size_t size = sizeof(phoneNum) / sizeof(int);
for (int i = 0; i < size; i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
for(int i = 0; i < size; ++i)
{
printf("\r\n %i \n", phoneNum[i]);
}
return 0;
}
sizeof(phoneNum) will return number in bytes, not length of array.
after the includes you could make a define like #define SIZE 10 and use SIZE like if it was a constant.
#include <stdio.h>
#define SIZE 10
int main()
{
int phoneNum[SIZE];
for (int i = 0; i < SIZE; i++)
{
//Do Something
}
}
Take into account the fact that strings should end with null terminated character (\0) so the size of the string have that space available.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
My code:
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
printf("%d", menu[i]);
}
I'm trying to ask the user for input and add it to the array and then at the end to output the whole array e.g 1,2,3,4....16, however as of now it always returns the value 16 no matter what the user input.
You need to run loop twice. Once for taking inputs and then for displaying all numbers.
#include <stdio.h>
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
{
printf("%d\n", menu[i]);
}
}
Your code has an array index bound check failure.
printf("%d", menu[i]);
The value of i here is going to be 16 because you are using it after the loop. The loop terminal condition is i == 16. The menu array is only defined for index values of [0..15]. The value you see in the output is entirely random depending on the state of the execution stack. You could test this by printing instead menu[65] and see random data or maybe a segmentation fault.
Printing out the array to the console is the same loop as your input, but with the printf embedded in it instead. So your code should have 2 loops in it. One loop to gather input, and the other loop to output the input.
The answer is in the comments.
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
printf("%d ", menu[i]);
you can add a loop at the end of your code like this
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for (i = 0;i<16;i++)
{
printf("%d ",menu[i]);
}
}
"I'm trying to ask the user for input and add it to the array and then at the end to output the whole array"
Just because it has not been suggested yet...
This can be done using a single loop, or with no loops at all.
(The looping option below is an adaptation of your code with comments describing differences.)
//The following items, are optionally
//defined here instead of in-line with code.
//they are used to clean up the scanf() and sprintf() calls below
#define data menu[0],menu[1],menu[2],menu[3],menu[4],menu[5],menu[6],menu[7],menu[8],menu[9],menu[10],menu[11],menu[12],menu[13],menu[14],menu[15]
#define input_data &menu[0],&menu[1],&menu[2],&menu[3],&menu[4],&menu[5],&menu[6],&menu[7],&menu[8],&menu[9],&menu[10],&menu[11],&menu[12],&menu[13],&menu[14],&menu[15]
const char input_format[] = {"%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d"};
const char format[] = {"%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n"};
//it also preferred to avoid magic numbers when possible
#define ELEMENTS 16
#define MAX_LEN_INT 11
//to demonstrate both looping and sequential methods to input and output the same thing
#define USE_LOOP 1 //change to zero for doing this with no loops
int main(void)//added void
{
int menu[ELEMENTS] = {0};
//char buffer `output` should accommodate room for max number of
//characters expressed in 32bit `int` data type: `11` (from the value: `-2147483648`)
//times count of elements to be output: ELEMENTS plus NULL terminator + punctuation.
//This should do it:
int size = ELEMENTS*MAX_LEN_INT+ELEMENTS + 1;
char output[size];//buffer for outputing final line showing user input values
memset(output, 0, sizeof(output));
#if USE_LOOP
int i;
printf("Input array values:\n");//moved outside the loop to display only once
for(i = 0; i < ELEMENTS; i++)
{
printf("enter value %d:\n", i+1);//prompt user for each input value
scanf("%d", &menu[i]);//scan value into array element
}
#else //Use sequential data entry
printf("Enter %d space delimited integer values (eg: 1 2 -45 78... 123) then <enter>:\n", ELEMENTS);
scanf(input_format, input_data);
#endif
//again, outside the loop to display only once
//place all data into printable buffer
sprintf(output, format, data);//using short representations of format specifier and data for readability
printf("%s", output);
return 0; //added return to comply with int function type.
}
Tested with largest possible number of digits using sequential method:
I'm trying to create an array which has size depended upon input elements count. After that I want to print it but I'm getting very strange outputs.
int main(void)
{
int input_arr;
int i,size=0;
int arr[size];
while(input_arr!=-1){
printf("enter positive int");
scanf("%d",&input_arr);
arr[size]=input_arr;
printf("%d",arr[size]);
for(i=0;arr[i]!='\0';i++){
printf("%d ",arr[i]);
}
size+=1;
}
return 0;
}
33 3 3 3 3 3 6487488 enter positive int3.
It gives output like this and after a while it stops taking elements. I could not recognize where am I doing wrong.
In C the size of the array is fixed the moment you define it. Increasing the size variable does not increase the array size. Therefore you immediately get a buffer overflow the moment you read the first element. You can instead declare a large array like this:
static const int maxSize = 4096;
int arr[maxSize];
int main(void)
{
int i, size=0;
while(size < maxSize){
printf("enter positive int");
scanf("%d", &arr[size]);
++size;
for(i=0; i < size; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
return 0;
}
Alternatively you can use malloc and realloc to grow the array dynamically.
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: ");
I'm trying to create a program which randomly decides how many cards you have, then randomly allocates a value to each of those cards.
I have managed to randomise the amount of cards, and I know how to randomise their values using an array and a for loop, but the problem is that this method only works when I manually choose a value for the number of elements in the array, but I want the number of elements to be the random amount of cards.
How do I go about this?
Here's my code so far to show what I mean. And yes, I'm aware the code probably could be done better but this is my first C assignment and I'm a complete beginner.
Thanks :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(void)
{
system("cls"); /* Clears output to start */
srand(time(NULL)); /* Sets seed for random number generator */
int player1_amount = rand() %9 + 2; /*Generates random number for player 1's amount of cards */
int player2_amount = rand() %9 + 2; /*Generates random number for player 2's amount of cards */
int a = 1; /* For loop purposes */
while(a <= 1) /* While loop to print out each player's amount of cards once */
{
printf("Player 1 you have %d cards! \n", player1_amount);
Sleep(500);
printf("Player 2 you have %d cards! \n", player2_amount);
a++;
}
Sleep(1000); /* Delays for 1 second before printing card values */
int values[3]; /* Creates an array with 3 elements, but I want the number of elements to be player1_amount from above */
int b; /* Random variable for the loop */
int size = sizeof(values) / sizeof(values[0]); /* Gets length of array */
for (b = 0; b < size; b++) /* For loop randomises 3 values and then stops */
{
values[b] = rand() % 10 +1;
}
printf("Player 1 your cards are"); /* For loop to print out the values one after the other */
for(b = 0; b < size; b++)
{
printf(" %d, ", values[b]);
}
getch();
return 0;
}
I believe you will want to use malloc or calloc for that with a pointer.
int *values = (int *)calloc(player1_amount, sizeof(int));
Just make sure you free your allocation when done:
free(values);
C allows you to declare variable sized array. If you are not interested in using functions like malloc or calloc you can simply use variable to declare array as I've done here :
#include <stdio.h>
void main()
{
int x;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
int array[x];
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
This program runs correctly without any error. So your problem is solved here itself without using malloc or calloc. But just make sure you declare your array after scanning or giving value to your variable which will represent the size of your array(here : x is the variable) and in your case I guess : player1_amount.
But still if you want to use malloc then here it goes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int x , i;
int * array;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
array = (int *) malloc(x * sizeof(int));
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
Both the codes will give you same output.
A little explanation ...
Malloc will take input parameter as the amount of memory you wish to allocate to given variable(like 'array' in our case) in bytes and will output the pointer to that block of memory.
Since here we are working with integer array the return type is cast as : (int *), had it been a character array we would type cast it as : (char *).
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.