Using scalar variable or a pointer to print 2D arr

2019-03-04 18:01发布

问题:

How do I use a scalar variable or a pointer to print 2D string array? The program needs to execute the system command “echo” to print out all the strings

Input:

char myarray[2][10] = {"Hello", "World"};
for (j=0;j<2;j++){    
    setenv ("myvar", myarray[j]);
    system("echo $myvar");       
}

Actual Output:

Hello
World

Expected Output:

Hello World

回答1:

You see that your problem can be solved by simply avoiding new line character in echo. By using man command on echo (man echo) we can see

-n do not output the trailing newline

So we can do this by replacing

system("echo $myvar"); 

by

system("echo -n $myvar"); 


回答2:

Use -ne

system("echo -ne $myvar"); 

Will leave the cursor at the start of the line containing the Hello.



回答3:

I found the exact solution. However I am still not using pointer/scalar variable.

char myarray[2][10] = {"Hello", "World"};

for (j=0;j<2;j++){    
setenv ("myvar", myarray[j]);
system("echo -n $myvar' '");      
}


回答4:

How do I use a scalar variable or a pointer to print 2D string array

Arrays under certain condition decay to a pointer to their 1st element. One of those case is when they get assigned (to the right pointer variable).

char myarray[2][10] = {"Hello", "World"};

is a an array of array of char. So myarray[0] is an array of char[10]. A char[10]'s 1st element is a char.

You can do

char * p = myarray[0];

Then p points to myarray[0]'s 1st element. It points to myarray[0][0]. p gets the address of myarray[0][0] assigned.

Following this you can modify your code like this:

for (j = 0; j < 2; j++) {    
  char p = myarray[j];
  setenv ("myvar", p);
  system("echo $myvar");       
}

The code uses p to print.

Still there a easier ways to print in C:

#include <stdio.h> /* for printf() */

...

for (j = 0; j < 2; j++) {
  char p = myarray[j];
  printf("%s", p);
}