Dynamic Arrays C -- Farhan#75
Dynamic Arrays C -- Farhan#75farhanf wants to merge 4 commits intobloominstituteoftechnology:masterfrom farhanf:master
Conversation
codejoncode
left a comment
There was a problem hiding this comment.
Great job so far Farhan, better practice to set all allocated data to NULL.
arr->elements = calloc(capacity, sizeof(char *)); in your create _array function
https://www.tutorialspoint.com/c_standard_library/c_function_calloc.htm
https://stackoverflow.com/questions/8106782/when-should-i-use-calloc-over-malloc
codejoncode
left a comment
There was a problem hiding this comment.
Farhan for your arr_append method consider the following:
```// Copy the element and add it to the end of the array
char *new_element = strdup(element);
//strudup is malloc and strcpy combined together
//allocates memory for the size of the string and then copys the string
arr->elements[arr->count] = new_element;```
is preferred over 'arr->elements[arr->count] = element' where element is the string passed in.
This is because if you don't make a copy of the of the element then if the original string is changed your array will be affected by this.
Take this Python code in consideration:
```temp = {"number": None}
arr = []
for x in range(2):
temp["number"] = x
arr.append(temp)
print(arr)```
And this is why we are learning C the final output will look like this: [{'number': 1}, {'number': 1}]
So the last update to "number" affected both index's because they both point to the same thing in memory.
https://repl.it/@codejoncode/AlienatedLinenLevel <<< play with it yourself.
No description provided.