Get length of array passed into a function in C [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How can I pass an array into a function and retain information about its length without passing the length separately?
[self Q&A - better answers than mine below]

In C, arrays can't be passed entirely to a function and hence it is not possible. When you pass an array name then it decays to pointer to the first element. Using sizeof operator would not help you in any way because it will give you the size of pointer.
Either you pass the size of array to the function or use a sentinel value at the end of array.
#include <stdio.h>
int size(int *a)
{
int count = 0;
while(*a++ != -1)
count++;
return count + 1;
}
int main(void)
{
signed int a[] = { 3, 5, 7, 9, 10, -1};
printf("size of array is: %d\n", size(a));
}

AFAIK If you pass an array as a pointer, there is no way to know its length in C. The length has to be provided by the caller.

Summing things up:
either provide a sentinel value that marks the end of the array
or pass the size of the array to the callee
The only two methods that actually work.

You can pass the length separately, like many do. Another perhaps impractical way is that you could pass a pointer to the array itself and retrieve the length from there.
EDIT #2: Removed the version with the global variable since it's bad practice. I'm reposting the old solution, which though rigid was less tedious and less dangerous.
EDIT #3: Replaced the original with something that at least shows how this could be useful.
#include <stdio.h>
void printArray(char (*p)[10]);
int main(void){
char p[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
printArray(&p);
return 0;
}
void printArray(char (*p)[10]){
for(int i = 0; i < sizeof (*p); i++)
printf("%d ", (*p)[i]);
printf("\n");
}
Output:
0 1 2 3 4 5 6 7 8 9

Related

How to give a size using realloc? [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 9 months ago.
Improve this question
I want to give a random size to pointer and I want to add some elements to the pointer. I want to give place to the pointer enough size. For example, if I have 10 elements in pointer, I want to give place 40 byte to pointer. But when I looked to my code, initially I gave so much size for the element.
I want to see as an output:
67
11
64
7
67
11
64
7
23
81
88
35
12
5
7
The size of memory=40
#include <stdio.h>
#include <stdlib.h>
int main() {
int *k;
int i=0,j=0,t=0;
int array[20]={67,11,64,7};
k=malloc(5*sizeof(int));
k=array;
for(i=0;i<4;i++){
printf("%d\n",k[i]);
}
k=realloc(k,50*sizeof(int));
k[4]=23;
k[5]=81;
k[6]=88;
k[7]=35;
k[8]=12;
k[9]=5;
k[10]=7;
for(j=0;k[j]!='\0';j++){
printf("%d\n",k[j]);
}
k=realloc(k,(j+1)*sizeof(int));
for(t=0;k[t]!='\0';t++){
printf("%d\n",k[t]);
}
printf("the size of the memory=%d \n",j*4);
printf("the size of the memory=%d \n",t*4);
return 0;
}
You can't resize an automatic variable like array which is what you are trying to do since you do k=array; (and leak the memory previously allocated).
You can copy the data from array into the allocated memory pointed out by k instead:
int array[20] = {67, 11, 64, 7};
int *k = malloc(sizeof array);
memcpy(k, array, sizeof array);
The loop condition you use is a tad confusing though:
for (j = 0; k[j] != '\0'; j++)
I suggest comparing with 0 instead.
The "the size of the memory" that you print out at the end is however not accurate. The size of the allocated memory at the end is (j+1)*sizeof(int), that is, 12 * sizeof(int), since k[11] is the first element being 0.
A word of caution is also in place: Your program currently has defined behavior because the array does contain 0:s in the positions [11, 19]. Just be aware that the extra memory allocated by realloc contains indeterminate values, so had your original array been only 11 elements big, you had read those indeterminate values when you compare with \0 (or preferably 0) and you would never know what the result would be. It could continue searching for \0 out of bounds.
Note: Don't forget to free(k); when you're done with it.

why sizeof doesn't give the length of the array? [closed]

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 8 years ago.
Improve this question
When I use sizeof in printf function, it return the length, but if I assign to any int variable it doesn't give the length of the array. Instead the program stops.
Here's the code:
int main(void) {
int a[] = {1, 3, 5, 6, 23, 55, 93, 923, 112, 33, 5, 23};
int len = sizeof(a)/sizeof(a[0]); // It return anonymous integer
int len2 = sizeof(a);
// mergesort(a, 0, len); // This is an update, because of this, program stops.
printf("%d\t%d\n", sizeof(a)/sizeof(a[0]), len);
printf("%d", len2); // The program stops when using this.
}
Update: Guys, sorry for the question. It's my mistake. It works fine, because I'm working with mergesort algorithm. It's an error in mergesort I think.
#Acme has a good thought, using printf() format specifier %d for a size_t value is wrong.
On my Linux amd64 system, sizeof(int) = 4 and sizeof(size_t) = 8. That might be a problem.
It seems to work fine for me (perhaps the lack of a newline character after the second printf() statement is confusing you?) but due to the size_t vs int format specifier mismatch, the results are undefined.
$ ./size
12 12
48$

Why a for loop isn't considered 'stylish' by my teachers? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I had to write a piece of code which would search a given value in an array.
I made this piece of code, which works:
#include <stdio.h>
int index_van(int searchedValue, int array[], int lengthArray)
{
int i ;
for (i = 0; i < lengthArray; i++)
{
if (array[i] == searchedValue)
{
return i;
}
}
return -1;
}
int main()
{
int array2 [] = {0, 1, 3, 4, 5, 2};
printf("%i", index_van(2, array2, 6));
}
With the correction (the teacher put up online) of this exercise the notes of my teacher were:
You have to quit the moment you have found your value ,so you can't search through the entire table if you have found your value already. A for-loop therefore isn't tolerated.
Even if the for-loop has an extra built-in condition, THIS ISN'T STYLISH!
// One small note ,she was talking in general . She hasn't seen my version of the exercise.
So my question to you guys is, is my code really 'not done' towards professionalism and 'style' ?
I think she's implying that you should use a while loop because you don't know how many iterations it will take to get you what you're looking for. It may be an issue of her wanting you to understand the difference of when to use for and while loops.
"...Even if the for-loop has an extra built-in condition..."
I think this right here explains her intentions. A for loop would need a built-in condition to exit once it's found what it's looking for. a while loop already is required to have the condition.
There is nothing wrong with your code. I have no idea if using a for loop is less stylish than using another, but stylish is a very subjective attribute.
That being said, don't go to your teacher and tell her this. Do what she says, a matter like this is not worth contradicting your teacher for. Most likely this is just a way to teach you how while loops work.
After accept answer:
I've posted this to point out sometimes there is so much discussion of "style", that when a classic algorithmic improvement is at hand, it is ignored.
Normally a search should work with a const array and proceed as OP suggest using some loop that stops on 2 conditions: if the value was found or the entire array was searched.
int index_van(int searchedValue, const int array[], int lengthArray)
But if OP can get by with a non-const array, as posted, then the loop is very simple and faster.
#include <stdlib.h>
int index_van(int searchedValue, int array[], int lengthArray) {
if (lengthArray <= 0) {
return -1;
}
int OldEnd = array[lengthArray - 1];
// Set last value to match
array[lengthArray - 1] = searchedValue;
int i = 0;
while (array[i] != searchedValue) i++;
// Restore last value
array[lengthArray - 1] = OldEnd;
// If last value matched, was it due to the original array value?
if (i == (lengthArray - 1)) {
if (OldEnd != searchedValue) {
return -1;
}
}
return i;
}
BTW: Consider using size_t for lengthArray.

How to create n number of arrays based on user input in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to prompt the user to enter a number, and then have the computer create that many arrays.
For example if the user entered the number 5, I would would want 5 integer arrays called array1[64], array2[64], array3[64], array4[64], and array5[64] to be created.
You can use array of pointers
Like following :-
int n,i;
//enter n
int **array = malloc(sizeof(int*)*n);
for(i=0;i<n;i++)
array[i] = malloc(sizeof(int)*64);
/* Do Stuffs*/
/* Free Memory */
for(i=0;i<n;i++)
free(array[i]);
free(array);
Anytime you say, "I want N variables of the same type named var1, var2, var3, ..., varN", what you really want is an array; in this case, you want an array of arrays.
Assuming that you know the second dimension at compile time (i.e., it's always going to be an Nx64-element array of int), then this is easy:
#include <stdlib.h>
...
size_t numArrs = 0;
// get numArrs from user
int (*arrs)[64] = malloc( sizeof *arrs * numArrs );
Presto - you've allocated an Nx64 array of int that you can access like any normal 2D array:
arrs[i][j] = some_value();
arrs[0] is your first 64-element array of int, arrs[1] is your second 64-element array of int, etc.

c programming Ascii values [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let us say that the English alphabets A to Z has value start from 1. A = 1, B = 2, C = 3 and so on. Write a program which calls a function which accepts the name of a person which is constant character array and returns an integer value with sum of the Alphapets. What is the benefit of passing the name of the person as const char array?
Suppose somebody else provides me a function that takes non-const char * and does the job. What the function is actually implemented is like this:
int get_int_sum(char *name)
{
int sum;
//codes to calculate sum of alphas
name[0] += 1;
//continue
return sum;
}
When I call the function using
char my_name[] = "Yu Hao";
int reuslt = get_int_sum(my_name);
Even if I got the result I want, my_name is changed to "Zu Hao" without my notice. However, if a function has a prototype of
int get_int_sum(const char*name)
I am sure that the string I passed will not be modified.
One advantage is that elements in a array are protected from changing its value.
For example, here is simple code.
int Your_function(const char * a)
{
a[3] = 'A'; // this statement causes compile error.
// do something
return 0;
}

Resources