Ian Cameron Arrays in C#68
Ian Cameron Arrays in C#68codypeak wants to merge 8 commits intobloominstituteoftechnology:masterfrom
Conversation
codejoncode
left a comment
There was a problem hiding this comment.
Good job so far Ian as we discussed when zoomed calloc would be a better practice for this scenario so you may want to update your code from arr->elements = malloc(capacity * sizeof(char *)); to arr->elements = calloc(capacity, sizeof(char *));
codejoncode
left a comment
There was a problem hiding this comment.
Ian 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.
codejoncode
left a comment
There was a problem hiding this comment.
char *arr_read(Array *arr, int index) {
// Throw an error if the index is greater than the current count
// Otherwise, return the element at the given index
if (index > arr->count)
{
fprintf(stderr, "index can not be greater than count");
}
else
{
return arr->elements[index];
}
}
This should be
char *arr_read(Array *arr, int index) {
// Throw an error if the index is greater than the current count
// Otherwise, return the element at the given index
if (index > arr->count)
{
fprintf(stderr, "index can not be greater than count");
}
return arr->elements[index];
}
No description provided.