1

How can I represent this C code in Delphi?

static char *mylist[] = {"aaa", "bbb", "ccc", NULL};

I can create my array as of

keywords : array[0..3] of string;
keywords[0] := 'aaa';
keywords[1] := 'bbb';
keywords[2] := 'ccc';
//Compiler error -> E2010 Incompatible types: 'string' and 'Pointer' 
keywords[3] := nil; 
6
  • null is C - use nil in Delphi. Commented Apr 18, 2014 at 22:27
  • Oooops I have nill in my code. Edited the post, thank you. Commented Apr 18, 2014 at 22:30
  • Ah. Well, actually you should just be able to do pchar instead of string. Commented Apr 18, 2014 at 22:38
  • 1
    This question is missing information that is relevant. What does the C code do with the array mylist after this single line? (How to represent it properly in Delphi depends on how the resulting array is being used. Most of the ways you'd use it don't need that construct at all.) Commented Apr 19, 2014 at 1:50
  • Exactly. Question is incomplete. Commented Apr 19, 2014 at 7:07

2 Answers 2

6

char* in C/C++ is PAnsiChar in Delphi, eg:

const
  mylist: array[0..3] of PAnsiChar = ('aaa', 'bbb', 'ccc', nil);

Or:

var
  mylist: array[0..3] of PAnsiChar;

mylist[0] := 'aaa';
mylist[1] := 'bbb';
mylist[2] := 'ccc';
mylist[3] := nil;
Sign up to request clarification or add additional context in comments.

1 Comment

This would be the correct approach if the requirement was interop. Pass such a thing to a different module. Otherwise you would never do this.
2

In Pascal, arrays and strings are a distinct type from pointers, so you can't assign the nil pointer.

You probably don't need a special token to terminate your array anyway. This is a C idiom.

If you want to loop through your array, simply do this :

for word in keywords do
    writeln(word)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.