开发者

Segmentation fault while dealing with 2 dimensional C strings

char *input[2]; 

input[0] = cat /etc/passwd
input[1] = grep root

I am trying to create a 2 dimensional array of C strings such that

char **dArray; 

dArray[0][0] = 开发者_JS百科cat
dArray[0][1] = /etc/passwd
dArray[0][2] = NULL   // Append NULL to mark end


dArray[1][0] = grep 
dArray[1][1] = root
dArray[1][2] = NULL // Append NULL to mark end 

How do we do this?

// My Code 

char **p ; 
char *_p[2];

_p[0] = cat /etc/passwd
_p[1] = grep root

p = malloc(2 * sizeof(char*));

for(i=0; i<2 ;i++){
   p[i] = malloc(20 * sizeof(char));
}

strcpy(p[0],_p[0]);
strcpy(p[0],_p[0]);

printf("%s,%s",p[0][0],p[1]); // I except the output cat,grep root 


Since a string is already a 1 dimensional array you will need a 2 dimensional one to store groups of groups of strings that is unrelated to the strings themselves and every top element should be allocated before being used.

Something like:

char ***dArray = malloc(sizeof(char**)*2);

dArray[0] = malloc(sizeof(char*)*3);

dArray[0][0] = "cat";
dArray[0][1] = "/etc/passwd";
dArray[0][2] = NULL;

dArray[1] = malloc(sizeof(char*)*3);

dArray[1][0] = "grep";
...


Your problem is this line:

printf("%s,%s",p[0][0],p[1]); 

p[0][0] is not a string/char* - you've used %s , so printf expects a string. p[0][0] is a char, the first character in your first array.

Use printf("%s,%s",p[0],p[1]);

Also, you've copied a string into p[0] twice, there's garbage in p[1]. Make sure you copy from _p[1] to p[1] as well.


Here is a version without using malloc.

#include <stdio.h>

const char *cmd1[] = { "cat", "/etc/passwd", NULL };
const char *cmd2[] = { "grep", "root", NULL };
const char **dArray[] = { cmd1, cmd2, NULL };

int main(void)
{ 
  for (const char ***cmd = dArray; *cmd; cmd++) {
    printf("command\n");
    for (const char **arg = cmd[0]; *arg; arg++) {
      printf("  argument %s\n", *arg);
    }
  }
  return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜