[Techtalk] C Programming Question

Sujita Purushothaman sujita at mimos.my
Wed May 29 16:30:47 EST 2002


This works too. Thanks.
"S. Gwizdak" wrote:

> > Hi,
> >     I'm having a problem with pointer-to-array in C.
> > I have to use the structure char  *somename[ ] . I also
> > need to store/assign data to the strings halfway thro the
> > program. ( I know I can initialise it as :
> > char  *somename[ ] = {"data1","data2"}; etc.
> > At some point in the program I need to change "data1"
> > to "somethingelse1" . How do I do that?
> > Thanks in advance.
>
> Ok, here's a representation of your data structure:
>
>  somename
>  |
> +-+
> |0| ------------> data1\0
> +-+
> |1| ------------> data2\0
> +-+
> |2| ------------> data3\0
> +-+
>
> So, let's play with some code:
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
>
> int main() {
>     char *p;
>     char *somename[] = {
>                          "data1",
>                          "data2",
>                          "data3"
>                        };
>
>     printf("%s\n", somename[1]);
>     p = strdup("somethingelse1");
>     somename[1] = p;
>     printf("%s\n", somename[1]);
>
> }
>
> strdup() is a cute little function that will malloc() some
> memory, and copy the string you just sent it, into that memory.
>
> I then tell somename[1], which happens to be a pointer, to point
> at an area of memory that now contains "somethingelse1\0".
>
> --
> /* S. Gwizdak  http://www.unf.edu/~gwis0001       */
> int q[2561];main(y){putchar(y%80?(q[y]=y==40?1:y>80?
> q[y-81]^q[y-79]:0)==1?42:32:10);y==2560?:main(++y);}




More information about the Techtalk mailing list