if i have 2D array char info [2][8];
[2 9 0 5 J O H N]
[3 5 5 2 1 i a n ]
if i want to show [0][1]
it should show '9'
i tried this one puts(info[0][1]);
it didn't seem to work
any idea?
cheers
This is a discussion on New with 2D array within the C Programming forums, part of the General Programming Boards category; if i have 2D array char info [2][8]; [2 9 0 5 J O H N] [3 5 5 2 ...
if i have 2D array char info [2][8];
[2 9 0 5 J O H N]
[3 5 5 2 1 i a n ]
if i want to show [0][1]
it should show '9'
i tried this one puts(info[0][1]);
it didn't seem to work
any idea?
cheers
This should work: printf ("%c\n", info [0][1]);
thanks
how can i copy it to another variable
i used like this but doesn't seem to be working
char temp[4];
for i=0;i<4;i++
strcpy(temp,info[0][i]);
should put [i] after temp?
i also tried temp[i]=info[0][i]; the value doesn't go through i think
any suggestion?
cheers mate
Just a small point...... If you are using these array as strings, you need to create the rows 1 longer than the string itself to allow for the NULL terminator.Originally posted by Unregistered
if i have 2D array char info [2][8];
[2 9 0 5 J O H N]
[3 5 5 2 1 i a n ]
As for copying parts of a string, you can do this a few ways. One is to use strncpy(), which allows you to copy upto n characters from one char array to another (just watch out the the null terminator that isn't necessary appended to the target). Or you can make a bit of code to do the copy yourself. Something like
Again, you will need to take care of NULL terminator if you intend to use these as strings.Code:for (i = 0; i < 4; i++) target[i] = source[i];
[EDIT] In your case, the source array in my sample code would be coded like this: source[0][i]
The 0 would be replaced with the relevant index number for the string you want to work with. Here's a working example:
Code:#include <stdio.h> int main(void) { int i; char *source[] = {"abcdefgh", "ijklmnop"}; char target[100]; for (i = 0; i < 4; i++) target[i] = source[0][i]; target[i] = '\0'; printf("source[0]: %s\n", source[0]); printf("target: %s", target); return (0); }
Last edited by Hammer; 05-04-2002 at 06:51 PM.
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]