How to change character string in function call?

W

Wavelet

I want have one string array and want to assign them in
one sub-function. After that,it will be used in main funcion.
But it seems the following code doesn't work.How can I
do it with pointer?

#include <stdio.h>
#include <stdlib.h>

char *str[] = {"word1","word2"};
void sub(char **p)
{

p = str;

}
main()
{
char** argv= NULL;
sub(&argv);
printf("arg[0]=%s\n",argv);
printf("arg[1]=%s\n",argv+1);
}

=========Result=======
[linuxred@vike tmp]$ a.out
arg[0]=(null)
Segmentation fault
 
W

Wavelet

#include <stdio.h>
#include <stdlib.h>
I found this version works. But too complex argument.

void sub(char ***p)
{
char str[100][100];
strcpy(str[0],"word1");
strcpy(str[1],"word2");

char ***q;
*p = str[0];
*(p+1) = str[1];

}
main()
{
char* argv[100];
sub(&argv);
printf("arg[0]=%s\n",argv[0]);
printf("arg[1]=%s\n",argv[1]);
}
 
R

Richard Bos

Wavelet said:
I want have one string array and want to assign them in
one sub-function. After that,it will be used in main funcion.
But it seems the following code doesn't work.How can I
do it with pointer?

#include <stdio.h>
#include <stdlib.h>

char *str[] = {"word1","word2"};
void sub(char **p)
{

p = str;

}

<http://c-faq.com/aryptr/pass2dary.html>
<http://c-faq.com/aryptr/ary2dfunc2.html>
<http://c-faq.com/ptrs/passptrinit.html>

Not a complete answer, but that should set you on the right track at
least.

Richard
 
X

xdevel

Wavelet ha scritto:

I found this version works. But too complex argument.

try this:

void sub(char **p)
{
*p = *str;
p++;
*p = *(str+1);
}


in main()

char *argv[2];
sub(argv);
printf("arg[0]=%s\n",*argv);
printf("arg[1]=%s\n",*(argv+1));
 
F

Fred Kleinschmidt

Wavelet said:
I want have one string array and want to assign them in
one sub-function. After that,it will be used in main funcion.
But it seems the following code doesn't work.How can I
do it with pointer?

#include <stdio.h>
#include <stdlib.h>

char *str[] = {"word1","word2"};
void sub(char **p)
{

p = str;

}
main()
{
char** argv= NULL;
sub(&argv);
printf("arg[0]=%s\n",argv);
printf("arg[1]=%s\n",argv+1);
}

#include <stdio.h>

char *str[] = {"word1","word2"};
void sub(char ***p)
{
*p = str;
}

int main() {
char** argv;
sub(&argv);
printf("arg[0]=%s\n",argv[0]);
printf("arg[1]=%s\n",argv[1]);
return 0;
}
=========Result=======
[linuxred@vike tmp]$ a.out
arg[0]=(null)
Segmentation fault
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,192
Latest member
KalaReid2

Latest Threads

Top