Skip to content

Dynamic Arrays C -- Farhan#75

Open
farhanf wants to merge 4 commits intobloominstituteoftechnology:masterfrom
farhanf:master
Open

Dynamic Arrays C -- Farhan#75
farhanf wants to merge 4 commits intobloominstituteoftechnology:masterfrom
farhanf:master

Conversation

@farhanf
Copy link
Copy Markdown

@farhanf farhanf commented Feb 26, 2019

No description provided.

Copy link
Copy Markdown

@codejoncode codejoncode left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

@codejoncode codejoncode left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants