# Pointers, pointers, pointers!

## Introduction

In the error outputs of some languages such as Java, a pointer is shown to give the programmer an idea of exactly where the error went wrong.

Take this example on Ideone:

Main.java:12: error: ';' expected
Invalid Java!
^


Notice the caret shows where the invalid code is?

## Challenge

Your challenge is: given number N and string S, place a pointer on the Nth character in S.

## Examples

Input: 2, "Lorem ipsum, dollar sit amet."

Output:

Lorem ipsum, dollar sit amet.
^


## Rules

• Input is received via STDIN or function parameters
• Output is printed out to the console or returned
• Trailing new lines, spaces etc are allowed in the output
• The pointer character must be a ^ caret and must be on a new line.
• This is code golf, so the shortest answer wins. Good luck!
• I feel like this is an extremely simple problem, so I am not certain it will be received overly well. You might want to try the sandbox once you have enough rep. – FryAmTheEggman Jun 10 '15 at 1:08
• I think this could have been made a bit more interesting if the input had multiple lines, so that you had to insert a newline, spaces, and carat at the correct position(s). Honestly, the spec doesn't really say it will be a single line, but I think enforcing that now will invalidate a few answers unfairly, since there's no example that shows this. – Geobits Jun 10 '15 at 2:04
• Like I said, the cat's probably out of the bag on this one. Rule changes after valid answers are posted usually don't work out well. Live and learn ;) – Geobits Jun 10 '15 at 3:06
• @SohamChowdhury I'll just pretend that was intentional ;) Do you want me to fix it? – monkeyonkeyboard Jun 10 '15 at 9:36
• While this may be very simple, you've certainly done well for a first challenge! You have +16/-0 votes, 1,300 views, and 28 answers (as of this writing) and you've made the Hot Network Questions list. Nice job! – Alex A. Jun 10 '15 at 14:50

# C 33

If just a function is allowed, then even c can compete.

(For the record, 2 bytes saved thx to @Cool Guy. Mt thx comment is unexpectedly evaporated.)

1 more char saved thx @Mig

f(a,c){printf("%s\n%*c",a,c,94);}

• C can always compete, it just can't always win. ;) – Alex A. Jun 10 '15 at 14:47
• @AlexA. <shrug> looks like its winning to me ;-) – Digital Trauma Jun 10 '15 at 15:05
• Save 1 char : f(a,c){printf("%s\n%*c",a,c,94);} – Michael M. Jun 10 '15 at 15:17
• If I were a cynical person, I'd say that it's still about 4 times as long as the shortest answer in a golfing language. Which is about business as usual. ;) This is clever, though. I think I had seen the * option in the format string before, but had completely forgotten about it. Might come in handy for some of the ascii art challenges in the future. – Reto Koradi Jun 12 '15 at 14:50

# Brainf*ck - 133 bytes

+++++>>+>>+++>>+++++++++<<<<<<[[->++++++++++<]>>]<++++<<++<<<<--<,>[->+<<->]>>>,<<[->>-<<]<<[->>>>++++++++++<<<<]>>+[,.]>.>[->.<]>>>.


Expects input as [0-9]{2}.* e.g. "02Hello world!!!" would produce

Hello world!!!
^

• Welcome to Programming Puzzles and Code Golf! This is a great first post, nice job! :D – Alex A. Jun 10 '15 at 14:46
• The problem is, no-one knows if this is even valid code, let alone solves the problem :) – Simon Jun 11 '15 at 21:46
• Yeah I think there is an off-by-one error here. The caret should be under the e in the example. At the cost of 1 byte this can be fixed by adding a - in front of [->.<] – FryAmTheEggman Jun 11 '15 at 22:47
• @FryAmTheEggman you're right -- see the edit. I originally had it under the e as it is now, but I got confused by using two IDEs with different fonts. – sudo rm -rf slash Jun 11 '15 at 22:54

# IA-32 machine code, 24 bytes

Hexdump:

66 b8 5e 00 42 38 22 75 fb 66 c7 02 0d 0a 42 42
c6 02 20 e2 fa 89 02 c3


It's a function (using MS fastcall convention) which updates the string in-place:

__declspec(naked) void __fastcall carrot(int n, char* s)


Assembly code:

    mov ax, '^'; // ah = 0, al = '^'

mystrlen:
inc edx;
cmp [edx], ah;
jne mystrlen;

mov word ptr [edx], '\r\n'; // append a newline
inc edx;

mymemset:
inc edx;
mov byte ptr [edx], ' ';
loop mymemset;

mov [edx], eax; // append a caret and terminate the string
ret;


It uses WORD-sized (16-bit) data in a few places. This has a penalty (1-byte prefix) in 32-bit code, but makes the code smaller anyway - using 32-bit data would put two zero bytes into code!

At the end, it writes 4 bytes (eax) instead of 2 bytes (ax) - the code is smaller that way, and 2 extra bytes of junk go after string termination, so no one notices them.

Usage:

int main()
{
char s[100] = "Lorem ipsum, euro sit amet.";
carrot(2, s); // credit to Digital Trauma for the name
puts(s);
}

• The instruction 66 b8 5e 00 moves 0x5e to al, not to ah, and zero to ah instead of al, so your comment in assembly code is misleading. – Ruslan Jun 13 '15 at 20:55
• @Ruslan Thanks! Fixed. That was a remnant from a previous version. – anatolyg Jun 14 '15 at 7:35
• Why is naked in there? And why is it the first thing I saw? – caird coinheringaahing Mar 28 '17 at 21:21
• It's Microsoft that decided to put the naked in front: msdn.microsoft.com/en-us/library/h5w10wxs.aspx – anatolyg Mar 29 '17 at 10:47

# Pyth, 8

zp\^*tQd


This solution no longer works, since the commit after the one I've linked to as the language name changed p to have arity 1. There are several other ways of achieving a similar score in Pyth that still work today, like zp+*dQ\^.

If the string needs quotes, adding v to the beginning of the code works. If it has to be comma separated, it goes up to 10 bytes:

eQp\^*dthQ

• I think this is the shortest one so far. Well done. – monkeyonkeyboard Jun 11 '15 at 4:51
• The algorithm seems wrong to me, I think ^ will always be under the first character. And by the way the input parameters are given in the wrong order to the online interpreter (so it fails executing). – Jim Jun 7 '17 at 8:32
• @Jim This answer used an older version of pyth, where p had arity 1. This caused the first line of the output to be printed first and then the caret on the next line followed by the spaces. Now you could do z+*dQ\^ for a shorter score but with a trailing newline, or add a p before the + to remove it. I'm unsure what to do here, since people upvoted this version of the answer, I think I will try to find the version it worked on. – FryAmTheEggman Jun 7 '17 at 13:33

# T-SQL, 90

While a fairly simple question, it's always interesting to try these in languages that really don't tend to support them well or golf well for that matter.

This answer is almost guaranteed to be the longest one.

This creates an inline table function for SQL Server that takes @n and @ as parameters and returns the results as a column. The carriage return is significant, otherwise I would need to use char(13).

CREATE FUNCTION G(@N INT,@ VARCHAR(MAX))RETURNS TABLE RETURN SELECT @+'
'+SPACE(@n-1)+'^'R


It's used in the following manner

SELECT R
FROM (VALUES
(1,'This is test 1'),
(2,'This is test 2'),
(3,'This is test 3'),
(4,'This is test 4'),
(5,'This is test 5')
)T(n,S)
CROSS APPLY G(n,S)


And returns

R
---------------
This is test 1
^
This is test 2
^
This is test 3
^
This is test 4
^
This is test 5
^

• Very creative use of a language not really designed for golfing ;) +1 – monkeyonkeyboard Jun 11 '15 at 4:52

## Python, 27

lambda n,s:s+'\n%%%dc'%n%94


This uses two levels of string formatting.

And here's a 25 byte solution partly stolen from feersum's answer (with the argument order reversed):

lambda*p:'%s\n%%%dc'%p%94


# Bash, 27

printf %s\\n%$[$1-1]s^ "$2"  ### Output $ ./carrot.sh 2 "Lorem ipsum, dollar sit amet."
Lorem ipsum, dollar sit amet.
^$ • Carrot? Also, what's the dollar at the end? – Scimonster Jun 10 '15 at 10:43 • The Dollar seems to be the shell's prompt. – M.Herzkamp Jun 10 '15 at 11:06 • @Scimonster Carrot was my attempt at a joke - see my edit to the question. And yes, the $ at the end is the shell prompt. The question specifies that trailing newlines are allowed, but doesn't say they're necessary. – Digital Trauma Jun 10 '15 at 15:04

# Python, 29

lambda n,s:s+'\n'+' '*~-n+'^'


Concatenates the string, a newline, n-1 spaces, and a ^.

• If only rjust wasn't so long... – Sp3000 Jun 10 '15 at 3:20
• Ah, the tadpole operator. – user253751 Jun 10 '15 at 11:46

# sed, 16

2y/1/ /;2s/ $/^/  This is something of a testcase of this meta answer. Specifically I am requiring that the number N is input in unary. E.g. for the caret in position 2, the input for N would be 11. Also it is not strictly specified which order S and N should be, so here S goes first, followed by unary N on a new line, all through STDIN. ### Output: $ { echo "Lorem ipsum, dollar sit amet."; echo 11; } | sed '2y/1/ /;2s/ $/^/' Lorem ipsum, dollar sit amet. ^$

• 2y/1/ /;2s/ $/^/ – manatwork Jun 10 '15 at 16:19 • @manatwork Good call! – Digital Trauma Jun 10 '15 at 16:24 # JavaScript (ES6): 63625652 32 bytes Thanks to nderscore for greatly reducing the size of the code. p=(a,b)=>b+\n${' '.repeat(a)}^


## Version that works across more browsers (47 bytes):

p=function(a,b){return b+\n${' '.repeat(a)}^}  • 1. The question uses 1-based indexing, so you need Array(a-1). 2. Anonymous function are allowed by default, so you don't need point=. 3. For the ES6 version, you can get rid of the return statement and the braces. Just use (a,b)=>b+"\n"+Array(a-1).join(" ")+" ^". – Dennis Jun 10 '15 at 4:00 • 33 bytes: (replace \n with an actual newline) p=(a,b)=>b+\n${' '.repeat(a-1)}^ – nderscore Jun 10 '15 at 4:20
• @dennis The indexing works perfectly for me: i.stack.imgur.com/Tdejc.png – adroitwhiz Jun 10 '15 at 4:21
• @Dennis Array(1).join(' ') results in an empty string :) – nderscore Jun 10 '15 at 4:21
• @nderscore I can't find a way to use an actual newline without it causing a line break in the code snippet, and the indexing follows the given example: i.stack.imgur.com/Tdejc.png – adroitwhiz Jun 10 '15 at 4:27

# CJam, 9 bytes

q~N@(S*'^


Try it online.

### How it works

q~  e# Read the input from STDIN and interpret it.
e# This pushes the integer and the string on the stack.
N@  e# Push a linefeed an rotate the integer on top of it.
(S* e# Subtract 1 and push a string consisting of that many spaces.
'^  e# Push a caret.


# Python, 29

Here's a more fun way to do it in 29:

lambda*p:'%s\n%*s'%(p+('^',))


Example usage:

>>> f=lambda*p:'%s\n%*s'%(p+('^',))
>>> print f('lorem',5)
lorem
^


# TI-BASIC, 10 (?) bytes

Disp Ans
Output(3,N,"^


Input is given in the variable N, as the question asks, but you can't use the letter var S as a string. In place of that, it takes string input from Ans, so to run the example in the OP: 2->N:"Lorem ipsum, dollar sit amet.":prgm<program name>.

I'm aware that that probably doesn't count, though, as each colon-delimited segment is technically a separate statement; here's a 46-byte program that takes input as N "S" (2 "Lorem ipsum, dollar sit amet.")

Input Str1
2+inString(Str1,"
//^there's a space after the quote
Disp sub(Str1,Ans,length(Str1)-Ans
Output(4,expr(sub(Str1,1,1)),"^


Both of these assume that the screen has been cleared before running.

• You'd be better off taking input from Input for the number and Ans for the string. – lirtosiast Jun 10 '15 at 1:59
• The first one also doesn't work if the program name, assignment, and string combined are longer than 16 chars. – lirtosiast Jun 10 '15 at 4:06
• @ThomasKwa 26, actually, since I have a color calculator :P It technically does work, if you count overwriting part of the input as 'working'. – M. I. Wright Jun 11 '15 at 5:02
• The first one does work if you add a ClrHome:Input N, because the current vote on meta for mixing I/O methods is at +7. – lirtosiast Jun 12 '15 at 14:39

# dc, 19

?pr256r^255/32*62+P


Input is from STDIN. dc strings are macro definitions and contained in [ ]. The string of spaces is generated by calculating the number that when expressed as a base 256 byte stream gives the string we need. The calculation is ((n ^ 256) / 255) * 32). This gives n spaces (ASCII character 32), but we need n-1 followed by ^, so we simply add 62 to the last base 256 digit.

### Output

$dc -e '?pr256r^255/32*62+P' <<< "2 [Lorem ipsum, dollar sit amet.]" Lorem ipsum, dollar sit amet. ^$


# C, 5957 47 bytes

f(a,c){for(puts(a);--c;putchar(32));puts("^");}


Pretty straightforward. Ungolfed version:

f(char* a,int c){
puts(a);        //Print the string first

for(;--c;)      //Until number-1 is not 0
putchar(32);//Print a space
puts("^");      //Print a caret
}


Test it here
Thanks to @anatolyg for saving 10 bytes!

• It's more beautiful to move puts(a) and putchar(32) into the parentheses of the for loop - there are exactly 2 empty places there! Also, I don't think you need to declare the type of a and c - just use the implicit int for them - will work if you don't do #include <stdio.h>. – anatolyg Jun 10 '15 at 8:57
• @anatolyg , Thanks! I did not think that omitting the types would work, but to my surprise, it did. – Spikatrix Jun 10 '15 at 9:09

# C# 55

A function, concept similar to my C answer, but this time return is shorter than output.

string f(string a,int b){return a+'\n'+"^".PadLeft(b);}


## SAS, 35 bytes

%macro a(n,s);put &s/@&n."^";%mend;


That is the SAS equivalent of a naked function; to add the data step to call it (equivalent to C main function to call it) would be a bit more (9 more bytes - Ty Alex), but I think that's not necessary for this purpose. How it would be called:

data;
%a(3,"My String");
run;


There is a macro-only implementation but it's much longer, even if you allow it to give a warning about invalid parameters on n=1.

If we could use pre-defined parameters, SAS would be quite short comparatively on this one, which is a rarity for a language most definitely not intended to be short.

If a dataset is allowed to be the source of input, which is how you would 'do it' in SAS (or by %let statements), but is probably not permitted, this is even shorter (27 bytes, which actually could be 25 if you guaranteed the dataset was constructed immediately prior to running this [as you could then just use set;]):

(pre-existing dataset)

data b;
n=3;
s="My String";
run;


(actual code)

data;set b;put s/@n"^";run;

• Good to see SO's resident SAS expert here on PPCG. :) – Alex A. Jun 11 '15 at 23:11
• I'm fairly sure some of the old timers who know DM scripting could best this score... And my cmdmac skills suck. – Joe Jun 11 '15 at 23:12
• I always forget that DM even exists, and I don't even know what cmdmac is! Btw, when you're counting bytes for the whole data step, you don't need data a;, you can just do data; which will save 2 bytes. But as you said, it's not necessary for this purpose anyway. – Alex A. Jun 11 '15 at 23:15
• Yeah, my SAS ingrained reflexes don't let me use that intuitively I guess :). Thanks. – Joe Jun 11 '15 at 23:17
• Speaking of old timers, I think you could save a couple bytes by defying all SAS intuition and using an old-style macro. I can't recall whether they can accept parameters though. – Alex A. Jun 11 '15 at 23:28

# Matlab/Octave, 41

@(n,s)sprintf('%s\n%s^',s,ones(1,n-1)+31)


This is an anonymous function that returns the string. This produces a warning, which can be suppressed by previously calling warning off.

• Do you mean the editor warning, or does it actually print a warning for you? Also, I beat you by 16 characters ;-) But mine does print the ans = bit, so after fixing that, it's only 10 characters difference. – Oebele Jun 10 '15 at 14:43
• @Oebele it prints a warning, but the returned string is unaffected. – FryAmTheEggman Jun 10 '15 at 16:55

# K, 21 bytes

{y,"\n",1_|"^",x#" "}


ryan@DevPC-LX:~/golf/caret$rlwrap k K Console - Enter \ for help 0:{y,"\n",1_|"^",x#" "}[2;"Lorem ipsum, dollar sit amet."] Lorem ipsum, dollar sit amet. ^  ## Explanation (x is the number, y is the string): { } enclosing function x#" " repeat the space x times "^", prepend the caret | reverse the string to put the caret at the end 1_ drop the extra space "\n", prepend a newline y, prepend the text  # R, 4948 46 As an unnamed function that outputs to STDOUT. Thanks to @Flounderer for the improvement. uses strwrap now to ident the caret to n-1. cat uses a seperator of \n rather than empty string. function(n,s)cat(s,strwrap('^',,n-1),sep='\n')  Test run > f=function(n,s)cat(s,strwrap('^',,n-1),sep='\n') > f(29,'The caret should point here v hopefully') The caret should point here v hopefully ^ >  • function(n,x)cat(x,"\n",rep(" ",n-1),"^",sep="") is 48 characters – Flounderer Jun 10 '15 at 22:37 • @Flounderer Thanks for that ... my original idea was similar to that, but I didn't do it as nicely – MickyT Jun 10 '15 at 22:45 • If I am allowed two initial spaces, this works: function(n,x)cat(" ",x,"\n",rep("",n),"^") and saves a few characters – Flounderer Jun 10 '15 at 23:09 • @Flounderer I suspect not. strwrap also has some possibilities but it would probably end up longer. – MickyT Jun 10 '15 at 23:23 • That's nice! I've never seen the strwrap function before. Is there a simple way of saying what it does? I can't figure it out from the documentation. – Flounderer Jun 11 '15 at 2:14 # Python3, 38 36 bytes def f(s,i):return s+'\n'+' '*~-i+'^' # OR def f(s,i):print(s+'\n'+' '*~-i+'^')  Test it here Thanks to @Dennis for saving 2 bytes! • (i-1) -> ~-i – Dennis Jun 12 '15 at 5:20 • I'm weak with bit operations and math.... Thanks anyway! :-D – Spikatrix Jun 12 '15 at 5:29 # Julia, 27 bytes (n,s)->s*"\n"*" "^(n-1)*"^"  This creates an unnamed function that accepts an integer and string as input and returns a string. To call it, give it a name, e.g. f=(n,s)->.... All that's happening here is we're appending a newline, n-1 spaces, and the caret. String concatenation is performed using * and string repetition with ^. Ungolfed: function f(n, s) s * "\n" * " "^(n-1) * "^" end  Example: julia> println(f(2, "Lorem ipsum, dollar sit amet.")) Lorem ipsum, dollar sit amet. ^  # PHP (CLI) - 42 <?=sprintf("%s\n%$argv[1]s",$argv[2],'^');  Call it from the command line: php pointer.php 2 "Lorem ipsum, dollar sit amet."  • I've only noticed now. But your answer is exactly like my 2nd option. I'm offering it to you: <?printf("$S\n%{$P}s",'^');. Replace the \n with a real newline. The total is 5 bytes. That only works on PBP4.1 and below. – Ismael Miguel Jun 10 '15 at 14:56 • Wow, so many mistakes in that comment... I meant that it is 26 bytes long and that only works on PHP4.1. And it is yours! – Ismael Miguel Jun 10 '15 at 19:59 # Matlab, 25 This one is extremely cheeky. Apparently displays prints non-printable characters as spaces. The following code defines a function named ans, that meets the specs. @(N,S)[S 10 ones(N-1) 94]  so calling this function like this: ans(2, 'Lorem ipsum, dollar sit amet.')  gives the output: ans = Lorem ipsum, dollar sit amet. ^  I always dislike the ans = part in Matlab answers. If this is a problem, I need to add 6 bytes... but I have always seen it like this in Matlab answers. Note that running this code overwrites the variable ans, so you need to redefine the function if you want to use it a second time! • Very nice! I didn't know putting a string in a vector worked like that. My understanding was that since this is a function, the string it returns it the meaningful value, and MATLAB's repl environment just happens to print it out. i.e. if you do x=ans(2, 'asdf'); you don't get an ans = thing. – FryAmTheEggman Jun 10 '15 at 16:55 My first shot at codegolf # Java, 133 65 String g(int i,String s){for(s+="\n";--i>0;)s+=" ";return s+"^";}  I'm sure it can be reduced even more. Old code public void go(int i,String s){System.out.println(s);IntStream.range(1,i).forEach(j->System.out.print(" "));System.out.println("^");}  • Can you store System.out somwhere? – Ismael Miguel Jun 10 '15 at 14:37 • No need for public. And change IntStream.range(1,i).forEach(j->System.out.print(" ")); to for(;--i>0;)System.out.print(" "); – Spikatrix Jun 10 '15 at 15:04 • @CoolGuy aha! sometimes simple is better – pallavt Jun 11 '15 at 5:00 • Can you move the s+="\n" inside the for() initialization to use the semicolon there? – lirtosiast Jun 11 '15 at 23:31 • @ThomasKwa 1 byte less – pallavt Jun 12 '15 at 5:03 # Swift, 41 It is disappointing that Swift does not have operator * on Array or String. {$1+reduce(0..<$0,"\n",{$0.0+" "})+"^"}

• For Swift 2.0: {$1+(0..<$0).reduce("\n"){$0.0+" "}+"^"} – Kametrixom Jul 22 '15 at 16:22 # SpecBAS - 34 1 INPUT n,s$: PRINT s$'TAB n-1;"^"  Apostrophe in PRINT forces a new line, then just have to move the cursor to correct position. # GolfScript 11 n@~(' '*'^'  Test here. # JavaScript - 52 bytes Here's mine, it's pretty simple. function f(n,s){return s+"\n"+Array(n).join(" ")+"^"}  Usage: $ console.log(f(7, "Any string at all"))

Any string at all
^


It points at the seventh character.

• Nice save Scimonster O_O – Florrie Jun 10 '15 at 15:10
• You can write it like alert((P=prompt)()+"\n"+Array(P()+1).join(" ")+"^"). And you save 2 bytes. Also, you can make it into a stasksnippet to showcase the code running. That expects the string to come first, then the position – Ismael Miguel Jun 10 '15 at 19:53

# Perl 5, 31

sub{"$_[0] "." "x($_[1]-1)."^"}
`
• You can save 2-3 characters. Drop the final newline as it's not required, then change the first newline to a literal newline. (Perl is okay with multi-line strings) – Mr. Llama Jun 10 '15 at 16:10
• @Mr.Llama thanks, those are good. – hobbs Jun 10 '15 at 16:12