counting the total element of a dynamic array [duplicate] - arrays

This question already has answers here:
Newbie questions about malloc and sizeof
(8 answers)
Closed 2 years ago.
I want to count the total element of a dynamic array.
I had search it on another source, and all I got just a static array.
How I can count it from a dynamic array?
Here is my code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
int sz, input, length;
printf("input size of array:");
scanf("%d", &sz);
arr = (int *)malloc(sz * sizeof(int));
for (int i = 0; i < sz; i++)
{
scanf("%d", &input);
}
length = sizeof(arr) / sizeof(arr)[0];
printf("Number of elements present in given array: %d", length);
return 0;
}
and the output i just get 1
PS D:\Materi Kuliah\1031101 DASPRO\Semester 1\Week-14\Review W6-W7> ./a
input size of array:6
1
1
2
2
3
3
Number of elements present in given array: 1

arr is a pointer type, sizeof(arr) is the size of a pointer on your system. To count the number of elements, you can either use the sz variable, or if you are using GCC, use one of the builtin functions for counting the number of elements.

Related

Why did the array lose the last element when passed into another function? [duplicate]

This question already has answers here:
Why isn't the size of an array parameter the same as within main?
(13 answers)
Closed 1 year ago.
I made an static int arr[3] and set to 1, 2, 3.
I can print 1, 2, 3 in the same function.
But when I pass the array it only prints 1, 2.
Why? What happened? How do I fix this?
#include <stdio.h>
void printArray(int* arr){
size_t n = sizeof(arr)/sizeof(arr[0]);
for(int i=0; i<n; i++){
printf("%d\n",arr[i]);
}
}
int* makearray()
{
static int arr[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
printf("The Array before passing onto stack\n");
size_t n = sizeof(arr)/sizeof(arr[0]);
for(int i=0; i<n; i++){ printf("%d\n",arr[i]);}
printf("\nThe Array when attempting to pass to another function\n");
printArray(arr);
return arr;
}
int main(void) {
int* m = makearray();
return 0;
}
By converting your array to a pointer, you removed the information that sizeof needs to know its total length.
Instead, it just gives you the size of a single int *, which is twice the size of a single int on your machine.
Hence, you only see the first two elements.
In C, you're basically forced to pass around the length alongside the pointer. You can wrap the two in a struct to make it easier to use, but don't expect the niceties of other languages you may be used to.

Array size and Pointers [duplicate]

This question already has answers here:
In C, are arrays pointers or used as pointers?
(6 answers)
Is an array name a pointer?
(8 answers)
Are empty arrays no longer allowed by gcc?
(4 answers)
Closed 2 years ago.
#include<stdio.h>
int main()
{
setbuf(stdout,NULL);
int a[],i,lim,sum=0;
printf("Enter the limit of the array: ");
scanf("%d",&lim);
printf("Enter the values: ");
for(i=0;i<lim;i++)
{
scanf("%d",&a[i]);
}
int *p;
for(p=&a[0];p<lim;p++)
{
sum=sum+*p;
}
printf("Sum= %d",sum);
return 0;
}
While running the code I'm getting the following error
..\src\Test6.c: In function 'main':
..\src\Test6.c:5:6: error: array size missing in 'a'
..\src\Test6.c:14:15: warning: comparison between pointer and integer
Please help me understand why I've to declare the array size when I have no issues doing the same without pointers.
Or please help me understand what change should I make to rectify the error:)
declare the size too when declaring the array.
eg.
int a[100000];
here you can put atmost 100000 elements in the array.
your loop
for(p=&a[0];p<lim;p++)
{
sum=sum+*p;
}
should be written as
for (p = &a[0]; p < &a[lim]; p++)
{
sum += *p;
}
or, more usually using index,
for (int index = 0; index < limit; index++)
{
sum += a[index];
}

How can I count the number of elements in my integer array [duplicate]

This question already has answers here:
C sizeof a passed array [duplicate]
(7 answers)
Closed 3 years ago.
I'm programming with the C language and I need to count how many elements are in the array to use further in the program.
Most online answers have arrays with like terms (Ex: 55, 66, 77) but my array will consist of random numbers.
An example of my array would be (4, 6, 77, 450, 0, 99).
The code i'm currently using to count the size is as follows, but the code doesn't work when 0 is an element of the array.
int size = 0;
while(*(arr+size) != '\0'){
size++;
}
And, I also tried to use sizeof but it also doesn't work. See the complete program below.
#define MAX 20
void display(int *arr);
main(int argc, char *argv[]) {
int array[MAX], count;
/* Input MAX values from the keyboard. */
int i; count=0;
while ( scanf("%d", &i) != EOF){
*(array + count) = i; // store in array[count]
count++;
}
/* Call the function and display the return value. */
printf("Inputs: ");
display(array);
return 0;
}
/* display a int array */
void display(int *arr) {
int size = 0;
int s2 = sizeof(arr)/ sizeof(arr[0]);
printf(" -- %d -- ", s2);
while(size <= s2){
printf("%d ", *(arr+size));
size++;
}
}
display is the function that is trying to count the elements in the array. s2 always returns value of 2, which is incorrect.
How can I count the elements of the array?
So, the only hard constraint I have seen stated so far is:
The caller of the function has to tell the function how many elements are in the array.
I'm not allowed to do that, only an integer array is to be given to the function
If this is true, then you will have to use a mechanism that is understood between the caller and the function for how to communicate the number of elements in the array.
One way to achieve this is to reserve one slot in your array to represent the size of the array. Since MAX is global to your program, your function can assume there is a number at MAX that represents the count.
int main () {
int array[MAX+1], count;
//... get input, calculate count ...
array[MAX] = count;
//... use the array ...
}
Now, when you call functions with the array, they can visit array[MAX] to find the size of the array.

C programming confused with output [duplicate]

This question already has answers here:
Weird behavior when printing array in C?
(5 answers)
Closed 9 years ago.
Can anyone please explain the output for the following program? I get an infinite loop if used a[i] = 0; and a segfault when I used a[i] = i; and also the i ranges between 0 - 9 when used a[i] = 0; whereas it goes to 39 when used a[i] = i; before giving a segfault.
#include<stdio.h>
#include<stdlib.h>
int mult(int a, int b);
int main()
{
int a[10];
int i = 0;
for(i=0; i < sizeof(a); i++)
{
a[i] = i;
printf("a[i]=%d i=%d\n", a[i], i);
}
return 0;
}
When you apply the sizeof operator to an array type, the result is the total number of bytes in the array, i.e, sizeof(a) determines the number of bytes in a which is not the number of elements in the array in this case. Use sizeof(a)/sizeof(a[0]) to get number of elements in the array a.
Replace
for(i=0;i<sizeof(a);i++)
with
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
Also, no need to initialize i twice.
You probably want to change this line:
for(i=0;i<sizeof(a);i++)
to this:
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
Note:
sizeof(a) gives the number of bytes in a[].
sizeof(a)/sizeof(a[0]) gives the number of elements in a[].
sizeof doesn't do what you think it does. It's returning the number of bytes occupied by the entire array.
You want the numeric length of the array, not the byte size.
Try something like this:
const int array_size = 10;
int a[array_size];
for (int i = 0; i < array_size; i++) {
a[i] = i;
printf("a[%d] = %d\n", i, a[i])
}
If you want to know how far to loop, without storing it in a separate const, use sizeof(a)/sizeof(a[0])

Creating a two dimensional array from a file input in C

TL;DR: Struggling with 2 dimensional arrays.
I'm trying to create two two dimensional array from a list of integers from a text file. This is programmed in C.
tester.txt contains:
2 1 2 3 4 5 6 7 8
The first number means that both arrays have 2 rows and 2 columns, if it were any other number the columns/rows would be represented as such.
tester.txt should ouput the following:
1 2 5 6
3 4 7 8
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,j,k;
FILE *filepointer;
int nrows;
int size;
fputs("Enter a filename: ", stdout);
fflush(stdout);
if ( fgets(filename, sizeof filename, stdin) != NULL )
{
char *newline = strchr(filename, '\n'); /* search for newline character */
if ( newline != NULL )
{
*newline = '\0'; /* overwrite trailing newline */
}
printf("filename = \"%s\"\n", filename);
}
filepointer=fopen(filename,"r");
fseek(filepointer, 0, SEEK_END); // seek to end of file
size = ftell(filepointer);
printf("Size=%d\n",size);
fseek(filepointer, 0, SEEK_SET);
int holderarray[size];
for(i=0; i<size; i++)
fscanf(filepointer, "%d", &holderarray[i]);
nrows=holderarray[0];
printf("Number of rows/columns=%d\n",nrows);
if (filepointer == NULL)
{
fprintf(stderr, "Can't open input file in.list!\n");
exit(1);
}
}
Everything works as expected up until this point. I can't visualize how to add the first half of the values to the new 2 dimensional arrays, hopefully you guys can help. Here's my brainstorming in codeblocks.
int matrix1[nrows][nrows];
int matrix2[nrows][nrows];
for (i=1; i<sizeof(holderarray);i++)
{
for (j=0;j<nrows;j++)
{
matrix[i][j]=holderarray[j];
}
for (i=0;i<sizeof(nrows);i++)
{
for (j=0;j<sizeof(nrows);j++)
{
printf("%d",matrix[i][j]);
}
}
return 0;
you can get them by looping using getc
1. you read the first char in line and define the array structure , cast to integer
2. initialize the arrays eg you read 2 so 2*2 is the size of the array, 3*3 is the size of the array and number of the elements to read in every array
3. continue reading in to reach the first array bound based 2*2 = 4 3*3= 9 based on the first line.
4. fill the other array since the first array is full,
You can't dynamically declare arrays in standard C like this based on variables that aren't known at compile time:
int matrix1[nrows][nrows];
int matrix2[nrows][nrows];
What you need to do, if you aren't using C99 or a later version, is use the malloc function that dynamically allocates memory for you:
int **matrix1, **matrix2;
int i;
matrix1 = malloc(nrows * sizeof(int*));
matrix2 = malloc(nrows * sizeof(int*));
for(i = 0; i < nrows; i++) {
matrix1[i] = malloc(nrows * sizeof(int));
matrix2[i] = malloc(nrows * sizeof(int));
}
Two-dimensional arrays in C are treated as pointers to pointers. Each pointer is a reference to a contiguous chunk of memory that contains integers (i.e. the rows of your matrix), and then we use a pointer to a pointer as a reference to another contiguous chunk of memory that contains references/pointers to the first element in all of these rows.
This image (not mine) may help: DYNAMIC 2D ARRAY
Note that this dynamically allocated memory should be freed when you are finished using it:
for(int i = 0; i < nrows; i++) {
free(matrix1[i]);
free(matrix2[i]);
}
free(matrix1);
free(matrix2);

Resources