How do you pass a character array - c

I want to pass an array of characters i.e. a String in c
int main()
{
const char c[]="Joseph";
TestWord(&c,&c);
return 0;
}
int TestWord(char tiles[], char word[])
{
return tiles;
}

#include <stdio.h>
char *TestWord(char tiles[], char word[]);
int main()
{
char c[]="Joseph";
char r;
r = *TestWord(c,c);
return 0;
}
char *TestWord(char tiles[], char word[])
{
return tiles;
}
You pass through the arrays without the & as arrays don't need those, as they are already somewhat like pointers, just like how you would scanf an array without the & symbol.
Don't forget that if you are returning tiles that you should save that in a variable.

you could pass a string(character array) in C in many ways.
This code passes the string a to the function PRINT. Note that in this method the base address of the array is sent to the function.
#include<stdio.h>
void PRINT(char b[])
{
printf("%s",b);
}
int main()
{
char a[]="hello";
PRINT(a);
return 0;
}

Related

How to return a string from a function to main()?

I have tried the following code but am getting an error:conflicting types for fun.Is there any solution that doesn't require the use of malloc.
#include <stdio.h>
int main()
{
printf("%s",fun());
return 0;
}
char* fun()
{
static char str[]="Hello";
return str;
}
It is because you have not declared prototype for fun.
#include <stdio.h>
char* fun(void);
int main()
{
printf("%s",fun());
return 0;
}
char* fun(void)
{
static char str[]="Hello";
return str;
}
C does not allow an array to be returned from a function, but it does allow a struct to be returned from a function. You can define a struct type to hold strings in an array, and return such a struct from your function to be copied into a receiving struct:
#include <stdio.h>
struct String
{
char body[1024];
};
struct String fun(void);
int main(void)
{
struct String my_string = fun();
printf("%s\n", my_string.body);
return 0;
}
struct String fun(void)
{
return (struct String){ .body = "Hello" };
}
char* fun()
{
static char str[]="Hello";
return str;
}
str hold base address of your string. (Assume 1000). Now when you return str, it'll return only base address.
printf("%s",fun());
Here you want to print string so you gave %s but this fun return base address of your character array(string) but not string (as you assume).
First, you need to dereference your fun() in printf so that it'll give first character of string array as str gave base address which points to first character of your string.
Also, you need to give formatter as %c so that it'll give H.
Now to print whole string, you need to increment what's inside your char pointer.
See below Code:
#include <stdio.h>
char* fun();
int main()
{
int i;
for(i=0;i<6;i++){
printf("%c",*(fun()+i));
}
return 0;
}
char* fun()
{
static char str[]="Hello";
return str;
}
Here you can see that I dereference fun() first to print the first character and then I made a for loop so that I can use loop variable i to increment what's inside in pointer returned by fun().
Try and let me know if you face any problem here.

return value of function is a string in C

I made some code in C with two functions.
One functions looks for a word (group of characters) and then saves it to a string. The other function shows what's inside the string. I can't find the right way to save the returning value to a string.
Here is my code:
#include <stdio.h>
char SchrijfString(void);
void LeesString(char);
int main(void)
{
char x[60];
x = SchrijfString(x);
LeesString(x);
return 0;
}
char SchrijfString(char x[])
{
printf("geef een string in: \n");
gets(x);
return x;
}
void LeesString(char x[])
{
printf("In de string zit:\n %s", x);
getchar();
}
The gets function is already populating x with a string specified by the user, so no need to return anything from SchrijfString or to assign anything to x back in main. Your function prototypes don't match the definitions. They need to be the same.
Also, gets is deprecated because it is unsafe. Use fgets instead.
void SchrijfString(char x[], int len);
void LeesString(char x[]);
int main(void)
{
char x[60];
SchrijfString(x, sizeof(x));
LeesString(x);
return 0;
}
void SchrijfString(char x[], int len)
{
printf("geef een string in: \n");
fgets(x, len, stdin);
}

C - Pass Array of Strings as Function Parameter

I need to pass a pre-allocated array of strings as a function parameter, and strcpy() to each of the strings within the string array, as in this example:
static void string_copy(char * pointer[]) {
strcpy(pointer[0], "Hello ");
strcpy(pointer[1], "world");
}
int main(int argc, const char * argv[]) {
char my_array[10][100];
string_copy(my_array);
printf("%s%s\n", my_array[0], my_array[1]);
}
And the resulting printed string would be 'Hello world'.
How do I pass a pre-allocated string array and fill out each string within a function as shown above?
When you are doing string_copy(my_array), you are passing a char (*)[100], i.e. pointer to char[100] array to your function. But your function is expecting a char *[], i.e. array of char pointers, because you have defined your function that way.
You can fix this by making changes so that your function (string_copy()) expects a char (*)[100], instead of a char *[].
For this, you can change your function definition as:
/* Your my_array gets converted to pointer to char[100]
so, you need to change your function parameter
from `char *pointer[]` to `char (*pointer)[100]`
*/
/* static void string_copy(char *pointer []) */
static void string_copy(char (*pointer) [100])
{
strcpy(pointer[0], "Hello ");
strcpy(pointer[1], "world");
}
* Alternative Solution *
A different design/solution would be to change in your main() function so that you are actually passing a char *[], which decays into a char ** - which is fine - to string_copy(). This way you would NOT have to change your string_copy() function.
int main(int argc, const char * argv[]) {
char my_array[10][100];
int tot_char_arrs, i;
char *char_arr_ptr[10];
/* Get total number of char arrays in my_array */
tot_char_arrs = sizeof(my_array) / sizeof(my_array[0]);
// Store all char *
for (i = 0; i < tot_char_arrs; i++)
char_arr_ptr[i] = my_array[i];
/* Actually passing a char *[].
it will decay into char **, which is fine
*/
string_copy(char_arr_ptr);
printf("%s%s\n", my_array[0], my_array[1]);
}
you need to use a pointer to the array. here is an example with 1 dimension array:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
static void string_copy(char **pointer) {
strcpy(pointer[0], "Hello ");
}
int main(int argc, const char * argv[]) {
char my_array[10];
char * p_array = my_array;
string_copy(&p_array);
printf("%s\n", my_array);
}
Your function can simply accept matrix dimensions and pass a const char * that stores the array of literals (pre-allocated) strings:
#include <stdio.h>
#include <string.h>
#define STRINGS_LENGTH 100
static void string_copy(size_t n, size_t m, char pointer[n][m], const char *strings_to_copy[])
{
for (size_t i=0; i< n; i++)
{
strcpy(pointer[i], strings_to_copy[i]);
}
}
int main( void )
{
const char *strings[] = { "hello", "World" };
char my_array[sizeof(strings)/sizeof(strings[0])][STRINGS_LENGTH];
string_copy(sizeof(strings)/sizeof(strings[0]), STRINGS_LENGTH, my_array, strings);
printf("%s %s\n", my_array[0], my_array[1]);
}
You can also change the structure of your code using dynamic allocation for your output array like:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
static bool string_copy(char *pointer[], const char *strings_to_copy[], size_t strings)
{
for (size_t i=0; i< strings; i++)
{
pointer[i] = malloc(strlen(strings_to_copy[i])+1);
if (pointer[i] != NULL)
strcpy(pointer[i], strings_to_copy[i]);
else
return false;
}
return true;
}
int main(void)
{
const char *strings[] = { "hello", "World" };
char *my_array[sizeof(strings)/sizeof(strings[0])] = {0};
if (string_copy(my_array, strings, sizeof(strings)/sizeof(strings[0])) )
{
printf("%s %s\n", my_array[0], my_array[1]);
}
for (size_t i = 0; i<sizeof(strings)/sizeof(strings[0]); i++)
free (my_array[i]);
}

How to send a pointer to a function?(This is different)

#include<stdio.h>
#include<conio.h>
int step_counter(char *array);
int main()
{
char *txt = "Try...";
printf("%d",step_counter(&txt));
getch();
}
int step_counter(char *array)
{
int step=0;
while(*array==NULL)
{
array++;
step++;
}
array-=step;
return step;
}
I need to send a pointer to a function without array. How can I solve this problem? I'm tired because of trying to solve this problem for months...
May be this is what you're trying to achieve.
#include<stdio.h>
int step_counter(char *array);
int main()
{
char *txt = "Try...";
printf("%d",step_counter(txt));
return 0;
}
int step_counter(char *array)
{
int step=0;
while(*array)
{
array++;
step++;
}
return step;
}
Edited
First, txt is a pointer to character array, so you don't have to send &txt to pass its address because txt itself is an address. And second, in the while loop you can either use while(*array) or while(*array != '\0') to check character array termination. And oh! as alk pointed out, array-=step; is redundant.

How to "return" an array from a function to main in c

I want to pass an arrays index from my function to main. How can I do that?
For example:
void randomfunction()
{
int i;
char k[20][10];
for (i=0;i<20;i++)
strcpy(k[i], "BA");
}
int main(int argc, char *argv[])
{
int i; for (i=0;i<20;i++) printf("%s",k[i]);
return 0;
}
I know that for you this is very simple but I've found similar topics and they were too complicated for me. I just want to pass the k array to main. Of course my purpose is not to fill it with "BA" strings...
You want to allocate the memory dynamically. Like this:
char** randomfunction() {
char **k=malloc(sizeof(char*)*20);
int i;
for (i=0;i<20;i++)
k[i]=malloc(sizeof(char)*10);
//populate the array
return k;
}
int main() {
char** arr;
int i;
arr=randomfunction();
//do you job
//now de-allocate the array
for (i=0;i<20;i++)
free(arr[i]);
free(arr);
return 0;
}
See about malloc and free.
Here is another option. This works because structs can be copied around , unlike arrays.
typedef struct
{
char arr[20][10];
} MyArray;
MyArray random_function(void)
{
MyArray k;
for (i=0;i<sizeof k.arr / sizeof k.arr[0];i++)
strcpy(k.arr[i], "BA");
return k;
}
int main()
{
MyArray k = random_function();
}
Simplest way:
void randomfunction(char k[][10])
{
// do stuff
}
int main()
{
char arr[20][10];
randomfunction(arr);
}
If randomfunction needs to know the dimension 20, you can pass it as another argument. (It doesn't work to put it in the [] , for historial reasons).

Resources