Ask your own question, for FREE!
Computer Science 13 Online
OpenStudy (anonymous):

c prog prob

OpenStudy (anonymous):

@slotema

OpenStudy (anonymous):

here's the task....it has to read the first line of the file and copy every word into a 2d array but for some reason.....the array is empty.....

OpenStudy (anonymous):

i tried two methods initially find the no.of character's in the file in the line 1 and create a dynamic array and copy the contents in to it.......(linear_array) then method 1: copy every char in to array ...if a space is encountered increment row pointer of 2d array method 2 : replace every space in the linear_array and replace it with \0 then copy each string into each row both of them dint work the array is either empty or copies a single word here's the test file used gcc

OpenStudy (anonymous):

You replace every space with '\0', Suppose the file contains "Hello, World". In your loop, you ask for strlen(p), which will be 6 on the first iteration (matching "Hello,"). This one is copied just fine. The second iteration however, p points to '\0' (what used to be the space). So strlen(p) is 0 the second iteration (and all other iterations). So strlen does NOT include the '\0'. Btw, don't forget to free the memory you malloced

OpenStudy (anonymous):

no i need it later so i cant free it yet.......that's not the entire prog thanks....but y dint the other method work like copying the array char by char?

OpenStudy (anonymous):

the one i commented out

OpenStudy (anonymous):

OpenStudy (anonymous):

i think i got ur xplanation but when i used strlen(p) i got a result of 5 like strlen("\0askldghal"\0") should give a zero?

OpenStudy (anonymous):

The problem with the commented code is the the else-part of the for-loop. You first increment k before assigning anything. Because of this, array[j][0] (the start of the string) will remain 0. strlen("\0askl...") will indeed give 0 length. You could also use the strtok function from the standard library to split a string into words (see: http://www.cplusplus.com/reference/cstring/strtok/ ).

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!