【发布时间】:2017-10-29 19:02:28
【问题描述】:
所以我正在尝试学习 ARM,并通过从 C 中获取字符数组指针、复制该字符串并返回指向不同字符数组的指针来练习。我已经编写了这段代码(注释了我假设我发生的事情):
.global copy @Let the linker know what's going on
copy: @Start
stmfd sp!, {v1-v6, lr} @Push stuff onto stack
mov r6, a1 @Put the pointer to the original string in r6
bl length @Get the length of the string
mov a1, r4 @Put length into the input parameter
bl malloc @Allocate enough memory for our new string
mov r9, a1 @Move the first memory location to r9
loop: @Loop to copy string
ldrb r8, [r6], #1 @Load first character from string and move pointer
strb r8, [a1], #1 @Store character in new string and move character
subs r4, r4, #1 @Subtract 1 from length
bne loop @Stop looping if string is done
mov a1, r9 @Move the start of the new string to the return value
b ending @Go to the ending
length: @Length function
mov r4, #0 @counter set to 0
countLoop:
ldrb r5, [r6], #1 @Load first character
cmp r5, #0 @Check for null character
add r4, r4, #1 @Add 1 to the length
bne countLoop @Loop if we're not at the end
mov pc, lr @Return the program
ending:
ldmfd sp!, {v1-v6, pc} @Pop stuff off the stack
.end
使用这个 C 驱动程序:
#include <stdlib.h>
extern char * copy( char str[] ) ; /* declare the assembly routine */
int main( int argc, char * argv[] )
{
char str[] = "abcd" ;
char * result;
result = copy( str ) ; /* call the assembly language routine */
printf("Will this work? %s", result);
exit(0);
}
但是我一直得到结果(null)。显然我的想法有些不对劲,但我不知道它是什么。任何帮助,将不胜感激!
【问题讨论】:
-
您的 C 代码包含类型错误。
printf%s接受char *,但您传递的是int。 -
改变让我什么都没有输出。我认为我的指针是空的,但我不知道为什么,因为我从 ARM 中返回了一些东西
-
您也可以将 str 设为 char*。我不明白你为什么不这样做。
-
@user2255853 如果您的指针为空,您的 C 程序就会崩溃。听起来您更像是在返回指向
'\0'字符的指针。 -
我认为
cmp r5, #0 @Check for null character add r4, r4, #1 @Add 1 to the length bne countLoop不会按照您的计划执行,因为bne想要使用来自cmp指令的状态,但add指令也设置了条件代码.