Initialize 2D char array by passing addresses

Hello guys, can i am trying to initialize a 2D char array with this code below

1
2
3
4
5
6
7
8
9
10
  static char c1, c2, c3, c4;

  c1 = 'a';
  c2 = 'b';
  c3 = 'c';
  c4 = 'd';

  char *input[] = {&c1, &c2, &c3, &c4};

  printf("%s\n", input[0][0]);


But it prints NULL.. but if use this code

1
2
3
  char *input[] = {"a", "b", "c", "d"};

  printf("%s\n", input[0][0]);


it works.. but i would like to inizialize the 2D array by passing variable addresses.. is it possible?

Thanks.
Your problem is more with the printf statement than the array. s requires a null-terminated string.

Try
printf("%c\n", input[0][0]);
in either example instead.


I don't think your second code should work. It should be const char *, not char *
Last edited on
I'm not sure what you are expecting to display, but:

1
2
3
4
5
6
7
8
#include <stdio.h>

int main() {
	const static char c1 = 'a', c2 = 'b', c3 = 'c', c4 = 'd';
	const char* const input[] = { &c1, &c2, &c3, &c4 };

	printf("%c %c %c %c\n", *input[0], *input[1], *input[2], *input[3]);
}


displays:


a b c d


If this isn't what you expect then you need to explain/show what is expected.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    static char c1, c2, c3, c4;

    c1 = 'a';
    c2 = 'b';
    c3 = 'c';
    c4 = 'd';

    char* input[] = {&c1, &c2, &c3, &c4}; // clearer maybe

    for(int i = 0; i < 4; i++) 
        printf("%c\n", input[0][i]); // <-- c not s, as previous

    return 0;
}


a
b
c
d
Program ended with exit code: 0
Topic archived. No new replies allowed.