This problem is driving me crazy, I’m sure I’m missing something. I need to initialize an array of chars using only pointers. Below is the code I have so far:
int p2(){
/* Implements problem 2 of lab */
// Create an array
char **s = (char**)malloc( 11 *sizeof(char));
char *p = *s;
char start ='A';
while( p != s+10){
*p = start;
start++;
p++;
}
return(0);
}
The problem I’m having is I don’t know how to address the characters inside of the array. I understand the base address of the array is **s, and the pointer to the first element is *s. What I don’t understand is how to get to **s+10 (i.e. the end of the array).
Can anyone shine some light for me??? Please!
EDIT: Ok, looks like I misunderstood the question. I appears I need to create an array of strings (thus the char ** allocation). Then I need to loop through this array, and assign each string (i.e. char *) a value 15 chars long. Please let me know if I’m understanding this correctly:
char **strings ==> strings[0 … n ] where each element is a pointer to a char (possibly an array). There for *string ==> strings[0], *(string+1) = strings[1], etc etc.
Am I close or way off?
char **sis 2 dimensional array of characters, or array of C strings if you want.If you want to use array of characters you should use:
If you really want to initialize array of strings, at first step you’re initializing array of pointers, that’s:
Please note that I’m using
char *inside sizeof. Than when you may use strings, but at first you must initialize each string.And there’s two way how to address your string:
Or if you want to use just pointers:
EDIT: added an example
When you have
**char pand usep++orp + 1, C increases memory address.*poperator tells compiler that you now want to work with data stored in memory, not with pointer. Therefor those two syntax do the same:So if you want traverse both your dimensions, you should use: