char* array of pointers modification [closed] - arrays

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
}

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

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.

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.

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