Making my own array in c: [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am beginner in C. I want to make an array whose size will be taken from user from scanf function because an array may have any size which is not known when program starts.
And how can I input array element as well:
I will like to have my program output as:
Please enter the number of array element: 4
Enter the elements: 12 43 5 6
The elements you entered are: 12 43 5 6
Is it possible to do this? How can I make my output like this?

Yes it is very possible. It is called dynamic memory allocation.
What you would do is create a pointer and then allocate it
later.
int *array;
int num_elements;
//Get number of elements here
array = (int *)malloc(sizeof(int) * num_elements);
if(!array){ //Good practice to check if the allocation worked
printf("Allocating %d bytes failed\n", (int)sizeof(int) * num_elements);
return -1;
}
//Use the array are normal
free(array); // don't forget to free allocated memory
Pointer access works just like a static array i.e. array[0] = whatever
edit:
Don't forget you should include stdlib.h when using malloc()

Dynamic memory work well to your purpose, however as mention earlier by Gopi, C99 allow you to directly use the stack.
Here is another solution using stack instead of heap memory:
#include <stdio.h>
int main(void)
{
int nb;
scanf("%d", &nb);
printf("%d\n", nb);
// declaration
char my_tab[nb];
if (nb > 2)
{
// I use my table as I want...
my_tab[0] = 'a';
my_tab[1] = 0;
printf("%s\n", my_tab);
}
return (0);
}
I hope this will help you understand better, the different kind of memory allocation.

A simple way of doing this with only basic knowledge might be to set the user input as a variable and then use that when you describe the size of the array:
#include <stdio.h>
int main(void)
{
int arraysize, i;
printf("Please input an array size.\n");
scanf("%d", &arraysize); //Will set the user input and use it as array size
getchar(); //Has user hit enter to continue
i = arraysize; //This is for sheer convenience in the for() loop
int array[i]; //This creates an array of the size inputted by the user
printf("Please input %d numbers to fill the array.\n", i);
for(i = 0; i<arraysize; i++) //Has the user put in a number for every space in the array
{
scanf("%d", &array[i]); //The i coordinate updates with the i++
getchar();
}
printf("Your numbers were: \n");
for(i = 0; i<arraysize; i++) //Same thing as the previous for() loop
{ //except we are printing the numbers in the table
printf("| %d |", array[i]);
}
}
The output looks like:
[PROGRAM BEGINS]
Please input an array size.
5
Please input 5 numbers to fill the array.
1 2 33 4 5
Your numbers were:
| 1 || 2 || 33 || 4 || 5 |
[PROGRAM ENDS]
Hope that helps!

Related

two different output in different console with same code in c? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
"getting different output in different console with the same code. I have used gcc compiler in vs code and dev c++ uses system compiler."
```C programming
int main()
{
int a=0;
int arr[a];
int i;
printf("enter the size of array:");
scanf("%d",&a);
for(i=0;i<a;i++)
{
printf("enter a %d no",i);
scanf("%d",&arr[i]);
}
for(i=0;i<a;i++)
{
printf("%d\n",arr[i]);
}
return 0;
}
```
The defect is that you declare int arr[a] (latter is a VLA) when a has been initialized to 0. This means no memory is allocated to arr, and when you write to it (via scanf) you undefined behavior.
You can use int arr[a]; if you declare it after you read the value of a. The problem is that there is no way to check for stack overflow (i.e. try set a to >8192 or whatever your stack size is set to and see what happens).
Try something along these lines:
unsigned a;
printf("enter size of array: ");
if(scanf("%u", &a) <= 0 || a == 0) {
// error handling
}
int *arr = malloc(a * sizeof(int));
if(!arr) {
// error handling
}
Use unsigned type for the variable a that holds a size and check that it's > 0 (I believe malloc(0) is not well defined on some platforms; on Linux it would cause malloc to return NULL hence trigger an error handling in the above code). Check all return codes for errors.

C Program stopped working after using scanf instead of var=0 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
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.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So I have this code:
#include <stdio.h>
#include <stdlib.h>
int functie ( int v[], int nr, int z)
{
int i,count;
scanf("%d", &z);
for(i=0;i<nr;i++) {
if(z==v[i]) {
count=count+1;
}
}
return z;
}
int main()
{
int i,nr,z;
fscanf("%d", &z);
FILE *f;
FILE *g;
f=fopen("data-in.txt", "r");
fscanf(f,"%d",&nr);
int *v=malloc(nr*sizeof(int));
for(i=0;i<nr;i++) {
fscanf(f,"%d",&v[i]);
}
g=fopen("data-out.txt", "w");
fprintf(g,"%d %d", functie(v,nr,z));
fclose(f);
fclose(g);
free(v);
}
and before I had int z=0; instead of trying to scanf my var z.
When I run this I get a stopped working error.
I have an array with numbers (integers) read from file, first line is the number of elements and second line the elements.
I need a var lets say z to check how many times an element appears in vector (check if scanned number z is equal to an element and +1 count )
example:
in file
4 (cuz I have 4 elements )
1 2 3 3 ( my elements )
than scan z as 3
z==3 true
count=1
again
count=2
Two issues here, both in main. First:
fscanf("%d", &z);
This function expects a FILE * for the first argument, which you didn't specify. Presumably you wanted to read from the console instead, so use scanf:
scanf("%d", &z);
Second issue:
fprintf(g,"%d %d", functie(v,nr,z));
Your format string is expecting two integer arguments, but you're only passing in one. Get rid of the extra format specifier:
fprintf(g,"%d", functie(v,nr,z));
fscanf will not be delimited by newlines. Best thing to do is eat through file a line at a time with fgets. So, add a line buffer to the top of main:
char line[16]; // assuming integers will actually be small
After opening your file as above with 'f':
if (fgets(line, sizeof(line), f))
{
int count = atoi(line);
int *v = (int *) malloc(count * sizeof(int));
for (int i = 0; i < count && fgets(line, sizeof(line), f); ++i)
{
v[i] = atoi(line);
}
}
You should absolutely add error checking to the above, which is minimal and for concept only (e.g. guard against bad input, buffer overflow, exceptions, count being wrong leaving you uninitialized integers at the end of the array, etc.) as this will only work if your input file is perfect. Note that 16 is generally a ridiculously small length for a line buffer. Also only do your logic against your vector if (a) the file opens, and (b) passes the first test, which is an integral number of entries.

how do i store a in an array in C? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm writing a program that calculates results of football matches.I'm trying to store the team ids' in an array with a length of 10 defined at the top but i keep getting getting a build error from the array. I realise the syntax might be wrong but how else can i use a variable to specify array length?
The error message i'm getting is : expected expression before '{ ' token.
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 10
int main() {
int numberofmatches, hometeamid, awayteamid, hometeamgoals, awayteamgoals;
int hometeamwins = 0;
int winratio;
int teamid[ARRAY_SIZE];
printf("Enter number of matches played \n");
scanf("%d", &numberofmatches);
if (numberofmatches > 0) {
int x = 0;
do {
printf("Enter match stats in order Home_team_ID,Away_Team_ID,Goals_Home,Goals_Away\n");
scanf("%d %d %d %d", &hometeamid, &awayteamid, &hometeamgoals, &awayteamgoals);
teamid[ARRAY_SIZE] = {hometeamid}; //Error is on this line
if (hometeamgoals > awayteamgoals) {
hometeamwins++;
}
x++;
}
while (x < numberofmatches);
winratio = hometeamwins / numberofmatches;
printf(" %d :teamidth %d :winratio", teamid[0], winratio);
}
return 0;
}
This
teamid[ARRAY_SIZE] = {hometeamid};
is the syntax for defining an array of size ARRAYSIZE and initialising it incompletely.
You try it in the middle of a loop.
In case you want to write to an array member you probably want
teamid[x] = hometeamid;
Also, I recommend making sure that you do not write beyond teamid[9], which is the last legal member of the array, for ARRAY_SIZE == 10.
Your defining an array of size 10, and then accessing it at index 10. Since arrays are indexed 0..n-1 you need to access index 9 to get the end of the array instead of 10.

Counting number of items in an array in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I keep getting the output of 100 when I do what everyone else online has been posting about:
int total = sizeof(num)/sizeof(int);
It doesn't seem to work for me. Here's my code:
int main() {
static int num[100];
int totalNum = sizeof(num)/sizeof(int);
return 0;
}
void readNumbers(int* num) {
int i = 0;
FILE *fp;
fp = fopen("/Users/Documents/hello.txt", "r");
if (fp == NULL) {
printf("Could not load file");
exit(0);
}
/* Loads numbers into num array */
int number;
while(fscanf(fp, "%d", &number) > 0) {
num[i] = number;
i++;
}
}
My output is 100 so I'm assuming there isn't anything that is inserted into the num array? And if I print out sizeof(num) it gives me a hundred; 4 bytes * 100 = 400.
Here is what is in hello.txt:
14 21 39 48 109 3882
Unlike arrays in other languages (that can grow and shrink, and will tell you how many elements the array currently contains), a C array is just a simple block of memory that has a fixed size. You declared an array that can hold 100 elements, and that's all sizeof is going to tell you.
If you want to know how many numbers you've put in the array, then you have to keep track of that in a separate variable. The array itself doesn't contain that information.

C array: showing big numbers as the output when its index goes out of bound [duplicate]

This question already has answers here:
Array index out of bound behavior
(10 answers)
Closed 8 years ago.
I was trying to test what output I would get when I tried to print the array that the index goes out of bound.
The code:
#include <stdio.h>
void main()
{
int arr[] = { 3, 4, 5 };
for (int i = 0; i < 5; i++)
{
if (arr[i] == 0)
{
printf("Breaking out of the loop.");
break;
}
else
printf("%i\n", arr[i]);
}
getchar();
}
When I run this code, the output is:
3
4
5
-858993460
3997200
I expected it to print out "Breaking out of the loop" and break out of the loop and terminate.
I truly have no idea how it even printed those numbers.
Any idea what those numbers mean?
P.S. I am sorry if this is a stupid question, I am quite new to C.
Memory out of bounds of an array, or dynamically allocated memory, doesn't belong to you, and its content is indeterminate. Accessing arrays or memory out of bounds leads to undefined behavior. Just don't do it.

Resources