Help with C pointers
Hello... i've started to learning C and i have a litle problem.
Lets say that i want to create an array to holds strings eg. "January","February","March" In C i have to create an array with pointers on it that point to another array each.. eg. ----------------------------------------------------------------------- #include <stdio.h> int main() { char *array[4]; // the array i want int i; for (i=0;i<=3;++i) //Reading the data to the array scanf("%s",array[i]); //eg.January for (i=0;i<=3;++i) printf("%s\n",array[i]) //printing the Data //eg. January // February // March return(0); } ----------------------------------------------------------------------- In the above code sth is going wrong. The results are not correct like the program doesn't shows the months correctly. This has to do with the reading or with the printing ? I'm i using the pointers the wrong way ?? please help. Thx A Lot ! |
That would be better (although still quite weak):
Code:
char array[4][16]; |
The pointers of your array point to random memory locations, and you have not reserved memory to store the strings.
This is more or less the simplest variation of your progrram that does work: Code:
#include <stdio.h> |
Your createing an array of pointers, but the pointers themselves are not set to anything.
The scanf function is trying to place information into the address that the pointers point to, it does not change the pointers to point at a new c string. try using this as the array statement. char array[4][80]; |
Thx a lot men !!
i just wander , is there any way to do it using an array of pointers instead of a 2D array ?? If there isn't one that means that this code: << char *array[]={"ONE","TWO","THREE"}; >> works only that way, i mean that i must store my strings to the array as above and then to access the array like "array[i]" I can't load the array data at run time with scanf("%s",array[i]). |
Quote:
<snip> sorry had a typo in malloc()<end snip> |
POOR (doesn't allocate memory for strings, will probably crash):
Code:
#include <stdio.h> Code:
#include <stdio.h> Quote:
Code:
#include <stdio.h> Quote:
|
Thx a lot men !
hey paulsm4 the 3rd way is really cool. The 1st has problem, i've tryied it in the past here's a simple solution for the 2nd one. Code:
#include <stdio.h> |
Quote:
Code:
#include <stdio.h> Quote:
|
Quote:
Because in C a string is an array of chars, an array of string is an array of arrays of chars. Using other method's like with malloc() or calloc() you may not see this directly in code, but it does not in change the fact that strings are arrays of chars. |
Quote:
|
Yea you are right....
|
Quote:
|
Quote:
C pointers and arrays are sometimes similar, but are fundamentally differents in the way they are initialized, affected and stored, even from a C code perspective. A C programmer has to know what kind of variables he is dealing with. Code:
char a[8]; // array |
All times are GMT -5. The time now is 01:06 AM. |