Help on array pointers

Vino akashvino79 at gmail.com
Thu Sep 14 14:21:09 UTC 2023


Hi All,

    Request your help to guide me in understanding about pointers, 
the below code works,I have few question which i need your help 
for better understanding.

Questions:1
```
char[] invalid = (cast(char*)malloc(char.sizeof * 
length))[0..length];
```
The above statement allocate memory for char type and the size of 
the allocated memory is char.sizeof * length so what is the use 
of this "[0..length]";

Question:2
```
char[]* invalidptr = &invalid;
```
Is this the right way to create a array pointer.

Question: 3
```
ST1: char[] invalid = (cast(char*)malloc(char.sizeof * 
length))[0..length];
ST2: char[]* invalid = (cast(char*)malloc(char.sizeof * 
length))[0..length];
```
What is the difference between the above to statement.

Question: 4
Who do we free the memory allocated.
Code:
```
auto ref testNames(in string[] names) {
	enforce(!empty(names), "Names cannot be Empty or Null");
		
	import core.stdc.stdlib;
         import std.algorithm: any, canFind;
        		
	size_t length = 20;
	char[] invalid = (cast(char*)malloc(char.sizeof * 
length))[0..length];
	char[]* invalidptr = &invalid;
		
	version(Windows) { (*invalidptr) = 
['\'','\"',':',';','*','&','[',']','-','+','$','#','<','>','{','}','(',')']; }
					
	foreach(i; names.dup) {
		auto result = i.any!(a => (*invalidptr).canFind(a));
		if(result) { throw new Exception("Invalid Name passed: 
%s".format(i)); }
		}
		string[] _names = names.dup;
		return _names;
	}
```
From,
Vino



More information about the Digitalmars-d-learn mailing list