I was practicing string arrays but it seems like i don't undestand how this works, can someone explain to me what would be a correct way to formulate this code?
AIM OF THE CODE: Assign 2 strings to an array of strings and print them by using a function.
ERRORS: The compiler doesn't find any error, but i simply don't get any output in the terminal.
#include <stdio.h>
#define MAX 100
void function(char **);
int main()
{
char *a[MAX]; /*array of max 100 strings*/
a[0] = "test0";
function(&a[MAX]);
return 0;
}
void function(char *a[MAX])
{
a[1] = "test1";
printf("%s",*a[1]);
printf("%s",*a[0]);
}
The compiler doesn't find any error, but i simply don't get any output in the terminal.
That's because you're passing the address of something that's not what your function expects.
function(&a[MAX]);
You're passing the address of the item at index MAX in array a, but your function interprets that as the address of the whole array. You should instead write:
function(a)
It seems like you've confused the way a parameter is declared with how it's used in a function call. When you declare a function, you have to specify the types of the parameters, so you say e.g. char *s[] to indicate an array of pointers to characters. But when you call a function, the compiler already knows what type the function expects, so you only need to pass a variable that matches the declared type. The square brackets in this context, like a[MAX], are interpreted as subscript that selects one element of the array.
Aside: As a matter of style, function is a terrible name for a function. I know this is just a tiny test program, so no big deal, but try to get in the habit of giving things descriptive names.
Also:
printf("%s",*a[1]); printf("%s",*a[0]);
Here you're accessing the item at index 1, but you haven't yet stored anything there. That's not a good plan. Either remove that first line, or change your code to store something in index 1.
Also, you don't need to dereference the elements. Each element in the array is an array of characters, and printf() will expect a value of type char *, which is what each a[n] will be. So just use:
printf("%s", a[1]);
printf("%s", a[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With