length of char array in C [closed] - c

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 8 years ago.
Improve this question
I have an array like this:
char data[512];
for clearing my array use:
memset(&data[0], 0, sizeof(data));
I defined:
#define NELEMS(x) (sizeof(x) / sizeof(x[0]))
but when I tried to get the the number of my array, it still gives 512;
int a = NELEMS(data);
I want to clear my array, then I add some element, How can I get the number of element inside my array (element inserted)?

data is an array of 512 char variable (1 byte), so the sizeof(data) is 512. This is correct. Read more about data types.

You seem to be only 'emptying' the array, and not removing it.
data will always be sizeof 512 as that is what you've initialized it. 'clearing it' of contents doesn't resize it, only deleting and recreating it will change size.
What you may want instead is
iterate through until a 'null' value is found (gets number of elements)
recreate a new array (with a different size) - not the best option
or, depending on what you're looking for
set a = 0;
As it stands, it looks like you wish to add a value to the next available space, and so the first bullet point here should be what you're looking for.
LINK:
Iterating through an array in C

There is no direct way to count the values you actually added to your "array".
If "data" is supposed to be a "string", and you want to know the number of bytes in your string, you can try strlen(data), assuming you always have a null-terminated content. But I doublt this is what you are trying to do.
If you(re looking for the first non-null char in your array, you will need to iterate using a WHILE loop.

You can keep track of how much you have in the array;
void add_char_to_array(char array[], unsigned int *index, char input)
{
array[(*index)++] = input;
}
void clear_array(char array[], size, unsigned int *index)
{
memset(&array[0], 0, size);
*index = 0;
}
int main()
{
char data[512];
unsigned int index = 0;
//do stuff
clear_array(data, sizeof(data), &index);
add_char_to_array(data, &index, a);
add_char_to_array(data, &index, b);
add_char_to_array(data, &index, c);
add_char_to_array(data, &index, d);
}
this will result in an data containing: ['a','b','c','d','\0','\0','\0'...] and index will contain 4 (the number of items in the array)

The memset() call zeroes out all elements of your array. (A string-processing function normally looks for 0 (equals '\0'))
Still that does not mean, that your array has 0 length now.
NELEMENTS() just returns the allocated memory for that array.
You should use a function for what you want to achieve:
int nElements(const char* x){
int i=-1;
while(x[++i]!=0);
return i;
}
(not tested)

Related

C can I return array instead pointer and if not can I work with pointer? [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
I'm creating this function that extracts a word or part of the string from a larger string, it works perfectly but I have to use strcpy to convert it from pointer to array, is it possible to return an array?
if not possible can I work directly with pointers?
I mean, using pointers instead of arrays this causes problems with header <string.h> functions ? Or I can use alla function without problem ?
#include <stdio.h>
#include <string.h>
char *substr(const char mainstring[], const int cstart, const int clength){
// printf(" %s \n ", substr("To many Strings", 8,7)); // = Strings
int main_length = 0;
int over_length = 0;
main_length = strlen(mainstring); // gets the length of mainstring[]
over_length = ( main_length - (cstart + clength)); // the value must be greater than -1 and less than the length of the mainstring[]
char *result = malloc(clength+1); // initialize by adding +1 for terminator \ 0
//That must be equal to or greater than 0 and less than the maximum length of the mainstring
if ( over_length >= 0 && over_length <= (cstart + clength)) {
strncpy(result, mainstring+cstart, clength); // copies the selected part to result
strcat(result, "\0"); // add terminator EOS end of string
}else{
printf("\n Error: Excessive size : %d", over_length); //shows when the condition is not met
}
return result;
}
int main(){
// use the function substr("String", start, length)
printf(" %s \n ", substr("To many Strings", 8,7)); // = Strings
return 0;
}
You cannot return an array as value because in most context an array automatically decays to the pointer to its first element.
Thus
return result;
is actually
return &result[0];
which is char* not char[].
There are workarounds described in answers in Returning an array using C. Especially, the one with wrapping an array with struct is interesting.
Btw. Symmetrically, it is not possible to pass an array as a function argument.
When you see
void fun(char arr[N])
it is a syntactic sugar for:
void fun(char *arr)
N is ignored.
Some consider using array arguments as a bad practice. Mostly, because arr is not an array in neither of contexts i.e. sizeof(arr) == sizeof(char*).
Actually, it is difficult to work with arrays:
it decays to pointers almost everywhere
passing arrays by value would be very costly
syntax for pointers to arrays require quite verbose typing

Inserting new values on vector (in C language) [closed]

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 2 years ago.
Improve this question
I'm trying to create a function which elaborates an array. I'm not sure how to input a vector or an array on a function and then returning the modified vector/array (I'm trying to use pointers).
Is this possible or I'm using pointers in the wrong way?
int newValue(int *p){
// modify the vector
return p;
}
int main(){
int a[6]={4,6,7,3,1,8};
int *p;
p = a;
p = newValue (p);
(This is the assignement:
Given an array of VET_SIZE elements of integers:
Write a function to insert a new value in a particular index of
the array, and move the following elements forward without
deleting existing values except for the value of last element)
I'm not sure how to input a vector or an array on a function and then reurning the modified vector (I'm trying to use pointers)
All you need to do is to pass the array itself, you can then modify it directly in function newValue. Something like this:
void newValue(int *p, size_t n){
// modify the 2nd item
p[1] = 10;
}
Then in main just call it:
newValue(a);
A couple of notes:
Your newValue does not need to return anything (void is ok), as you can change the array directly.
void newValue(int *p, size_t n) is the same as void newValue(int p[], size_t n) - because array decays to pointer.
Usually it's good to pass an additional parameter n about the input array size, so inside your function you can check to make sure you don't have out-of-bound access.

Reading into array [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 6 years ago.
Improve this question
Please help, I need to read an input txt file into an array and print it out put somehow I keep getting error message.
#include <stdio.h>
void reading_into_array(int A[]);
#define MAXVALS 100
int
main(int argc, char *argv[]){
int numbers[100], i;
reading_into_array(numbers[MAXVALS]);
for(i = 0; i < 100; i++){
printf("%d", numbers[i]);
}
return 0;
}
/*input information*/
void
reading_into_array(int A[]){
double inp;
int n = 0;
while(scanf("%lf",&inp) == 1){
A[n++] = inp;
}
}
numbers[MAXVALS] is out-of-range and its type doesn't match with the function argument. use numbers instead.
Avoid using values of uninitialized variables having automatic storage duration, which invokes undefined behavior. Initialize numbers like int numbers[100]={0},i;
When calling a function that takes an array as a parameter, you only need to supply the name of the array, e.g. numbers. "numbers[MAXVALS]" would supply the value of the MAXVALth element of this array. This is wrong for two reasons:
the function needs an array, not an element
The array has a size MAXVAL; its elements are counted from zero to MAXVAL-1, so the MAXVALth element does not even exist
If you want floating point numbers in your array, declare the array as double A[MAXVAL] everywhere.
Last note: the reading_into_array function should have a check that it will prevent it from putting more than MAXVAL numbers into the array, or you risk that it will corrupt memory and crash your program.

Error when passing a 2-dim array as function's parameter in C [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
I try to pass a two dimensional array as a parameter to a function like this:
void comb(int n, int array[n][n-1])
{
.....
}
And in the main function:
int main(int argc, const char * argv[])
{
const int p = 10;
int array[p][p-1];
comb(p, array); //Error:No matching function for call to 'comb'
return 0;
}
The "comb" function is declared above the main function. But Xcode gives me the error message on line "comb(p, array)" that "No matching function for call to 'comb' ".
I don't know how I could fix this. Also, is there some better way to pass a 2-dim array as parameter?
Your code is correct in C99.
If you get a compiler error, it could be because you are not showing the real code, or you are not invoking your compiler in C99 mode.
In C11 it is optional whether the compiler supports VLA, but your compiler documentation should indicate whether or not it is supported.
There is no other way to pass a VLA as parameter.
If your array dimension is known at compile-time then you can replace const int p = 10; with #define ARRAY_DIM 10 ; then your array will no longer be a VLA and the function can simply be:
void comb(int array[ARRAY_DIM][ARRAY_DIM-1])
{
Never passed a matrix, but when you pass arrays, the name is just the pointer to the first element.
char myArray[10];
where myArray is really a char pointer rather than a char.
You need to change something. Passing big things in functions is asking for a pointer
If comb take an array
void comb(int n, int array[n])
this should be put like
void comb(int n, int*array)
And then access to elements are in the fashion
*(array+k) ... // equals to array[k]
YOU CANNOT DO THIS
array[k] ... // Erro.
And call comb in main just in the way you did, since array names are already pointers
Not sure for bidimentional but almost sure the same, since bidim are just a big unidimensional array arranged in another way.
When passing pointer, function forget about boundaries.
Good practice is to help the function avoid disasters passing the max len
void comb(int n, int*array,int len)
{
int k=0;
While(*(array+k) !=n) // Search array for a number equal to "n".....
{
k++;
if(k>len)
return 0; // Avoid seeking outside the array, cut now. nice plase to return 0 (not found)
}
return 1; // got a hit before reaching the end.
}
Meanwhile in the main call:
comb(p, array, sizeof(array)/sizeof(array[0]); // third param is the number of elements

Find the size of integer or floating point array when array is in other file and function is in other file? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
I know this to find the size of array = sizeof(arr)/sizeof(arr[0])
But I have to implement the following (It's just a demo):
demo.h
#ifndef __DEMO_H
#define __DEMO_H
void heap_sort(int *);
#endif
demo.c
void heap_sort(int *ptrA)
{
//implementing heap sort
But here it requires length of array
}
main.c
#include "demo.h"
int main(void)
{
int A[10];
heap_sort(A)
return 0;
}
FYI .. It's just a demo.. but here I have to implement it in some other scenarios in which there is restriction that "DON'T CHANGE ANYTHING IN HEADER FILE" which means i can't change the function signature . Then how to get the array length in demo.c For char it's easy to get by help of strlen() Isn't there anything similar to get the length of int,float double types
The only alternatives I see are:
use a special value as terminator (as strlen does).
use the Pascal trick, and place array length in the first element.
store the array size in a global external variable.
use a separate function.
E.g.:
int arraySize(int newSize)
{
static int arraySize = 0;
int oldSize;
oldSize = arraySize;
if (newSize)
arraySize = newSize;
return oldSize;
}
in main.c:
arraySize(10);
in demo.c:
arraylen = arraySize(0);
if you can't change the function signature, then maybe you could pass the size of the array in the first element.
A[0] = 10;
heap_sort(A);
Or mark the end of the array with some special value, but I don't like this one because you'd have to iterate the whole array to find the length and you need to make sure this value is not used in the array:
A[LENGTH-1] = END//some value;
void array_length(A) {
while (*A++ != END) {
length++;
}
}
This is just a solution for the restrictions you imposed, what I would normally do, is either pass the size of the array as a second argument, or use a struct for the array:
struct array_t {
int *data; //allocate this
int size;
};
Note: other horrible solutions include global variables.
Thinking of strlen() is going into the right direction.
Strings are character arrays with a '\0' as array termination, as last element.
You could take the same approach for any other type of array.
Just define one value as the value which indicates the last element in an array. Searching for this value then helps you to find the size of the array.
Update:
I like mux's idea of using the first element in an array.
Anyhow, using it to store the numbers of element in there might lead to problems in case the number of elements in the array is larger as what can be store in an array's element (a char array, for example, whould then be limited to 255 elements).
My approach on the other hand has the draw back that the value used as terminator to the array is not usable as real value in the arra itself.
The combining the former and the latter approaches, I propose to use the first element of the array to store the value which is used as terminator of the array.
The constraint seems a bit odd, but whatever.
Why not use a global variable to store the size.

Resources