This question already has answers here:
Find the Size of integer array received as an argument to a function in c [duplicate]
(4 answers)
Closed 2 years ago.
I am a Python user for quite a time now and now try to get into C. While Python does a lot in background for me i now have to code in C in a much more 'BASIC' way. I like it,... but its hard.
The important part starts here
I really like the len() method in Python to get the length of an array. But in C it seems as if i have to look for the size (in bytes) of an array and divide it by the size (in bytes) of one element to get the length for the hole array.
If there is a simple or a more common way i would like to here about it. However i want to understand why the following program prints me different sizes for my array 'a'.
#include <stdio.h>
void print_array(int a[]){
printf("size of 'a' in the function is: %d\n", sizeof(a));
}
int main(void){
int a[5] = {0, 2, 4, 8, 16};
printf("size of 'a' before the function is: %d\n", sizeof(a));
print_array(a);
return 0;
}
The output is the following:
size of 'a' befor the function is: 20
size of 'a' in the function is: 8
At least i want to write a function that prints and array which i don´t know the length of. What how i understand, in C is only possible by looping truth it. This is the code i would add to the 'print_array' function. But it does it not how i aspected it to do because of the 'wrong' size.
int loop = sizeof(a)/sizeof(a[0]);
for(int i = 0; i <= loop; i++){
printf("Array[%d] = %d\n", i, a[i]);
}
Output (element 3 and 4 are missing):
Array[0] = 0
Array[1] = 2
Array[2] = 4
Thanks a lot for any explanation!
In C you must pass in not only the array, which decays to a pointer, but the size of the array as well. In C the common convention is (array, size):
void print_array(int a[], size_t s) {
for (size_t i = 0; i < s; ++i) {
... a[i] ...
}
}
Where you call it like:
print_array(a, 5);
Related
This question already has answers here:
How do I determine the size of my array in C?
(24 answers)
random number in while loop [C programming] [duplicate]
(2 answers)
How can one print a size_t variable portably using the printf family?
(14 answers)
Closed 2 years ago.
I'm writing a program in C to add random numbers to an array. The size of the array is given (say n = 250) and using rand(), I'm generating these numbers (range is 1 to 100).
int main()
{
int n = 250;
int array[n];
for (int i = 0; i < n; i++)
{
srand(time(NULL));
int r = rand()%100 + 1;
array[i] = r;
}
printf("Output Size: %lu\n", sizeof(array));
return 0;
}
When I run the code, the result is-
Output Size: 1000
Expected result is 250. What am I doing wrong?
I think you're expecting n as output (number of elements in the array); but you're doing it wrong. Currently, what you're getting is 250*4 = 1000 (i.e., size of int is 4, and the number of elements is 250).
Replace sizeof(array) with sizeof(array)/sizeof (array[0])
Read this to dive deeper.
sizeof(type) returns the size, in bytes, of the type.
To find out size of array, you can do:
printf("Output Size: %zu\n", sizeof(array)/sizeof(array[0]);
Also, the type of the result of sizeof operator is size_t. You should use %zu format specifier instead of %lu.
You have 250 elements array, each array element is of size 4 bytes.
250*4 = 1000.
And you don't need to call srand in loop.
read this article about srand.
I wrote two functions and call the functions in main.
Function 1 – I wrote a function that returns void and takes an int * (pointer to integer array) or int[], and int (for the size). The function needs to initialize all the elements of the array to non-zero values.
Function 2 – I wrote another function that returns int and takes an const int * (pointer to integer array) or int[], and int (for the size). The function should sum all the elements of the array and return the sum.
In main I defined an integer array of size 5. Called function 1 in main to initialize the values of the array. Called function 2 in main to get the sum and print the value of the sum to the console.
My problem is the program runs but the print out for sum we are getting is a large (in the millions), random, number and is not the expected answer of 15. Anyone who can help us get the correct answer would be greatly appreciated
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#pragma warning(disable: 4996)
void func1(int* ptr, int size);
int func2(const int* ptr, int size);
int main()
{
int grid[5];
func1(grid, 5);
func2(grid, 5);
}
void func1(int* ptr, int size)
{
*ptr = 1, 2, 3, 4, 5;
}
int func2(const int* ptr, int size)
{
int sum;
sum = ptr[0] + ptr[1] + ptr[2] + ptr[3] + ptr[4]; // *(ptr + 0); putting an asterisk makes it so that it changes the entire "ptr" value and the "[0]" value
printf("\n\nThe sum of the integers in the array is %d.\n\n", &sum);
}
*ptr = 1, 2, 3, 4, 5;
does not do what you think it does. It actually evaluates all the integer constants but sets ptr[0] to be 1 (see comma operator for more detail), leaving all the others at some arbitrary value.
Note that it is not evaluating *ptr = (1, 2, 3, 4, 5) (which would set *ptr to 5) but is actually evaluating (*ptr = 1), 2, 3, 4, 5 - this works because something like 42 is actually a valid C statement, albeit not very useful.
If you're trying to set the array to increasing values, just use something like:
for (int i = 0; i < size; i++)
ptr[i] = i + 1;
You probably also want to do that when summing the values since it should depend on the passed-in size rather than just summing five values:
int sum = 0;
for (int i = 0; i < size; i++)
sum += ptr[i];
Additionally, the value you are printing out is not the sum, it's the address of the variable containing the sum (a decent compiler will warn you about this). You should be using sum in your printf rather than &sum.
And, as a final note, the signature for func2 indicates that you should actually be returning the sum rather than just printing it. So I would suggest removing the printf from that function and simply doing:
return sum;
Then you can put the printf into the caller (main) as follows:
int main(void)
{
int grid[5];
func1(grid, sizeof(grid) / sizeof(*grid));
int sum = func2(grid, sizeof(grid) / sizeof(*grid));
printf("The sum of the integers in the array is %d.\n\n", sum);
return 0;
}
Note the use of sizeof(grid) / sizeof(*grid), which is basically the number of array elements in grid - this will allow you to resize grid by simply changing it in one place to something like int grid[42] and still have all the code work with the updated size.
Not actually necessary for your code but it's best to get into good programming habits early (more descriptive names for your functions may also be a good idea).
Line *ptr = 1, 2, 3, 4, 5; assigns ptr[0] value and leaves other spots unitilized so when you sum it, it will be random memory.
You should use for like this to initialize
for(int i=0;i<size;i++)
{
ptr[i] = i+1;
}
and similiar aproach to sum it.
I am new in c programming and I am studying arrays right now. I saw that unlike java you can't print them automatically by using Arrays.toString() method. I want to write a simple function that prints the array.
In the program it asks us the size of the array and when we write it, it asks what is the value for each element and then the program calls the displayArray() function to print the array on a single line.
For example :
Hello. What will be the size of the new array?
3
Enter the 1. element
7
Enter the 2. element
5
Enter the 3. element
1
The result should be "Your array is: 7 5 1" but instead of that I get "Your array is: 3 6356728 2" as a result. Can you help?
#include <stdio.h>
void displayArray();
int main()
{
int size;
printf("Hello. What will be the size of the new array?\n");
scanf("%d", &size);
int myarray[size];
for (int i = 0; i < size; i++)
{
printf("Enter the %d. element\n" , (i + 1));
scanf("%d", &myarray[i]);
}
displayArray(myarray[size], size);
return 0;
}
void displayArray(int myarray[], int size)
{
printf("Your array is: ");
for (int i = 0; i < size; i++)
{
printf("%d ", myarray[i]);
}
return;
}
You have a problem in the function call (which your compiler should have warned you about, read the footnote later)
displayArray(myarray[size], size);
should be
displayArray(myarray, size);
because,
Type mismatch between formal parameter and actual argument: you function expects an array (a pointer to the first element of the array, to be precise), not an element of the array.
undefined behavior. For an array defined as int myarray[size], accessing element like myarray[size] is off-by-one, as C arrays are 0-based indexing.
Footnote:
If you try to compile your code, compiler should complain about the mismatch. It can happen either
You did not turn up the compiler warning level (which is a mistake from your side)
or, you chose to ignore the warnings (which is an "offense" from your side)
It's a common mistake which beginners commit.
While calling a function in which you pass an array, you only need to specify the name of the array you want to pass.
I am trying to understand how malloc works. I did a program searches for the largest element in a one dimensional array int.
This is the code.
#include <stdlib.h>
#include <stdio.h>
void largest_element(int *nbr)
{
int i;
int n;
int m;
i = 1;
nbr = (int*)malloc(sizeof(nbr) + 8);
while (i < 8)
{
if (*nbr < *(nbr + i))
*nbr = *(nbr + i);
i++;
}
printf("%d ", *nbr);
}
int main(void)
{
int i;
int tab[8] = {11, 2, 4, 5, 9, 7, 8, 1};
int n = sizeof(tab)/sizeof(int);
i = 0;
largest_element(&tab[8]);
return(0);
}
The program works without malloc but how can I make it work with malloc? What did I do wrong and why does my code only give me garbage numbers?
I think you are lost with pointers and arrays so you can not understand malloc properly (no offense, everyone who is learning C do the same mistake).
Let's take your main function. When you run:
int tab[8] = {11, 2, 4, 5, 9, 7, 8, 1};
You staticly allocate an array of 8 integers and you fill it with your numbers.
The dynamic equivalent would be:
int* tab = malloc(sizeof(int) * 8);
tab[0] = 11;
tab[1] = 2;
/// Etc...
tab[7] = 1;
First thing: the first element of an array has the index 0. So in your largest_element function, i should be initialized at 0 instead of 1.
The reason is, when you deal with array, you deal with pointers. In your case, tab is a pointer to the first element of the array. So, when you do tab[3], you get the forth element of your array.
Second thing: when you do:
largest_element(&tab[8]);
You send to your function the eighth element after the begining of your array. The problem is: you do not own this memory area! You own the memory only until tab[7].
If you want to send the complete array to your function, just use:
largest_element(tab);
Now, let's talk about your largest_element function.
You do not need to call malloc here since the memory is already allocated
When you do *nbr = *(nbr + i); you change the value of the first element of your array. I think you wanted to do m = *(nbr + i); isn't it.
Why do you not use the nbr[i] instead of *(nbr + i)?
A correct implementation of this function would be something like (not tested):
void largest_element(int *nbr)
{
int i = 0;
int max = 0;
while (i < 8)
{
if (max < nbr[i])
max = nbr[i];
i++;
}
printf("%d ", m);
}
A last thing, using malloc involve using the function free to release the memory when you do not need it anymore.
What did I do wrong and why does my code only give me garbage numbers??
In largest_element(int *nbr) nbr points to the array tab in main (at least if you call it like this: largest_element(tab); instead of like this largest_element(&tab[8]);
Then you call nbr = (int*)malloc(sizeof(nbr) + 8); now nbr points to some allocated memory which has not been initialized and which contains garbage values. Now if you read from that memory it's normal that you get garbage values.
You simply don't need malloc for this problem, just as you don't need floating point math or file system related functions for this problem.
This question already has answers here:
Why does a C-Array have a wrong sizeof() value when it's passed to a function? [duplicate]
(6 answers)
Closed 7 years ago.
I've written a little program to determine the minimum element in an array a[]. When I debug, the program seems to be working fine initially but then the for loop in the min() function stops execution after two steps, despite the array being of size 10.
The final output is 23, when it sould be 3.
Is the code sizeof(a)/sizeof(int) incorrect? I found it on another article on stackoverflow.
#include <stdio.h>
#include <limits.h>
int min(int[]);
int main(){
int a[]={100,23,3,4,5,6,7,8,9,10};
printf("%d", min(a));
return 0;
}
int min(int a[]){
int min = INT_MAX, i;
for(i = 0; i < sizeof(a)/sizeof(a[0]); i++){
if((i>=0) && (a[i]< min))
min = a[i];
}
return min;
}
Inside the function, a is a pointer to integer array, so sizeof(a) returns the size of a pointer which is typically 4 or 8 bytes depending on the system. Saying that, it is not possible to count the number of elements in a C array using sizeof(a)/sizeof(a[0]) inside the function. You need to pass the number of elements explicitly as an argument to the function.
int min(int a[], int n) {
...
for (i = 0; i < n; i++) {...}
...
}
printf("%d", min(a, sizeof(a)/sizeof(a[0])));