Inserting new values on vector (in C language) [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 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.

Related

char* array of pointers modification [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 am new to c language after learning python and java and I encountered an interesting exercise that i cannot find answer online for.
Given an *char array of pointers to string (*char arr[N(N is defined)]={"sadsd","gasgs"......})
what is the proper way to pass given array of string pointers to a function so that the function will be able to modify the array?
For example if i want to print the array with a different position for each element in it? After i pass the array pointer to the function I cant modify the array for some reason without using [] do define the elements I want to work on. the exercise is to use pointer arithmetics without using [].
thank you and have a great day :)
Passing an array of strings to a function can be done with a declaration like this :
void function(char ** strArray);
The size cannot be found from such a pointer so it should be passed too :
void function(char ** strArray, int arraySize);
Indices are accessible with [] from 0 to arraySize-1. Pointer arithmetic allow doing the same with a different syntax :
strArray[5] // Gives a string (whose the size could then be found with strlen)
*(strArray + 5) // Equivalent form using pointer arithmetic
Here is an example printing the array content after having changed the second index :
void printStringArrayContent(char ** array, int size) {
*(array + 1) = "Margaret";
for(int i=0; i<size; i++) {
printf("%s ", *(array + i));
}
printf("\n");
}
void main(){
char * array[3] = { "John", "Sarah", "Michael" };
printStringArrayContent(array, 3); //==> John Margaret Michael
}

c - char array only prints first char [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 2 years ago.
The community is reviewing whether to reopen this question as of 2 years ago.
Improve this question
This is just a part of the code and it is simplified for this question.
I would like to be able to store the word into my struct, the whole word not just the first char.
struct lexics{
enum token token;
char lexeme[LEXEME_MAX];
};
int main(void) {
char a[]="";
a[0]='w';
a[1]='h';
a[2]='i';
a[3]='l';
a[4]='e';
struct lexics rs={WHILE_KEYWORD,*a};
printf("%s\n",rs.lexeme);
}
this only prints w and I need it to print while
I cannot use anything other than the char a[]="";
a must be build in this way
When I print result it is while but when I put inside the struct it is only w
By doing struct lexics rs = {WHILE_KEYWORD, *a};, you are effectively putting the first element of a inside of the lexics.lexeme array. Try using a function that copies the entire array:
struct lexics rs = {WHILE_KEYWORD};
strncpy(rs.lexeme, a, LEXEME_MAX - 1);
rs.lexeme[LEXEME_MAX - 1] = 0; // to be sure that the string is properly terminated :)
In your code
char result[]="";
does not give you an infinite-length array, it's a one element array (only null-terminator). You need to either have a proper size mentioned, or a long-enough initializer to have a proper size of the array.
struct lexics{
enum token token;
char lexeme[LEXEME_MAX];
};
...
struct lexics rs={WHILE_KEYWORD,*a};
printf("%s\n",rs.lexeme);
In C arrays are filled with zero if there are less initializers than elements in the array.
In your code you only provide 1 single char to initialize char lexeme[LEXEME_MAX] array. This means the array looks like "w\0\0\0\0..." and as a result only the first character is printed.
You must use strcpy or strncpy to copy the string from array a into the array rs.lexeme.

length of char array 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 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)

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

Explanation required - 3-D Arrays, Pointers [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 8 years ago.
Improve this question
I came across this snippet:
#include<stdio.h>
int main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
return 0;
}
Output: Garbage Value ---- 1
This was the explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access
the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.
However, I am still unable to understand the same. I would like the same to be provided in an easy to understand manner (Not that I am complaining about the above explanation).
Explanation on the 6th and 7th line may please be provided.
There are several problems with your code:
#include<stdio.h>
int main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
a is declared as a 3D array, but you initialize it with a 2D array.
int *p,*q;
p=&a[2][2][2];
p is initialized to an invalid memory location. Since a has only 2 elements per dimension, the only valid subscripts are 0 and 1.
*q=***a;
q has not been initialized to point to a valid location in memory. Derferencing q with *q is undefined behavior.
printf("%d----%d",*p,*q);
return 0;
}

Resources