Using scalar variable or a pointer to print 2D array

会有一股神秘感。 提交于 2019-12-02 23:33:35

问题


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);
}


来源:https://stackoverflow.com/questions/39911092/using-scalar-variable-or-a-pointer-to-print-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!