*sigh*
Sorry I meant X[3]. Or I meant the fifth word. It was just an oversight. I wouldn't make that kind of logical error in practice.
Zahlman, I didn't say I felt it was the only way.
I understand pointers and dynamic memory allocation. I was getting a little mentally tripepd up cuz there was a couple layers of indirection in the example I am working on so I was looking for a tip. I got the help I needed from cheap freelancer. My followup question (basically of the form 'is my understanding of this correct') was a simple yes or no question. And the answer was yes.
Dynamically allocating memory for an array of strings
Quote:Original post by cheap freelancerQuote:Original post by sharpnova
how would i do it with a double pointer to char?
i have something like that already:
int fileLength = 35;
char **X;
X = (char**)malloc(fileLength);
for(int i=0; i<fileLength; ++i ) X = (char*)malloc(50*sizeof(char));
i have no idea what i'm doing here to be honest.
is this the right way to do it?
it's hard for me to test. cuz most of my attempts are compiling and even working fine at runtime but i have no way of really knowing if i did it right (for example.. if i'm just getting lucky with not going out of the bounds of my assigned memory space)
EDIT: in the first malloc.. it gets seg fault so i fixed it to fileLength * 50.
so now my question is.. is there any redundancy here? i'm first saying that the size of X is going to be (amount of elements per array * size per element) but then in the for loop i allocate "size per element" for each element.. isn't this redundant?
X = (char**)malloc(fileLength*sizeof(char*));
replace ++i by i++
Please, as a favor to those that are beginners and are vulnerable to being led astray, consider learning the C/C++ language(s) properly before providing advice on the subject.
Hmm.. His suggestion worked. Was there something wrong with the correction he made? (it's what i'm using now)
No there was nothing wrong, you can check example given at kerningham and ritchie's c book.
//Removed spammish signature.
[Edited by - jbadams on October 27, 2007 6:31:16 AM]
//Removed spammish signature.
[Edited by - jbadams on October 27, 2007 6:31:16 AM]
The correction regarding malloc was correct.
And, technically, the correction regarding the increment wasn't wrong in itself, but the initial code wasn't wrong to begin with either so no reason to change it. Just unecessary confusion added for no use at all.
And, technically, the correction regarding the increment wasn't wrong in itself, but the initial code wasn't wrong to begin with either so no reason to change it. Just unecessary confusion added for no use at all.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement