一个有趣的C语言题目

myfan1212 2010-07-08 07:35:27
我在一个字符串中保存一串代码,然后实现代码功能 怎么能实现?
打个比方:
cahar* a="printf("OK")";
后面怎么写能执行那条语句 即在屏幕上输出 OK
...全文
193 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xtianliqi 2010-07-11
  • 打赏
  • 举报
回复
自己写个函数把它当参数传进去就可以
david-yue 2010-07-11
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 winterlc 的回复:]
脚本语言有这样的功能!
[/Quote]

貌似做不到,这个可以参考,或者自己做编译器,需要编译原理研究得很深入啊。
diablox0147 2010-07-11
  • 打赏
  • 举报
回复
做得到、、、、去找下叫libtcc的库
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <libtcc.h>

char ma_fonction[] =
"int soustraction(int a,int b) "
"{"
" return difference(a,b); "
"}";


int soustraire(int a, int b)
{
return a-b;
}

int main(int argc, char **argv)
{
TCCState *s;

int (*entry)(int,int);
void *mem;
int size;

s = tcc_new();
if (!s) {
fprintf(stderr, "Impossible de creer un contexte TCC\n");
exit(1);
}

tcc_add_symbol(s,"difference", soustraire);

tcc_set_output_type(s, TCC_OUTPUT_MEMORY);

if (tcc_compile_string(s, ma_fonction) != 0) {
printf("Erreur de compilation !\n");
return 1;
}

size = tcc_relocate(s, NULL);
if (size == -1)
return 1;

mem = malloc(size);
tcc_relocate(s, mem);

entry = tcc_get_symbol(s, "soustraction");

tcc_delete(s);

printf("%d \n", entry(10, 3) );

free(mem);
return 0;
}
ylu029 2010-07-09
  • 打赏
  • 举报
回复
楼主,你太有想象力了。
呵呵呵。
wangxipu 2010-07-09
  • 打赏
  • 举报
回复
晕,可以自己做编译器来
lvshaoqing 2010-07-09
  • 打赏
  • 举报
回复
难道要自己做解释器。。。
Lonelywolf1899 2010-07-09
  • 打赏
  • 举报
回复
printf("OK")

把这句话写到一个文件里,保存,再编译那个文件就好了

^_^
winterlc 2010-07-09
  • 打赏
  • 举报
回复
脚本语言有这样的功能!
liao05050075 2010-07-08
  • 打赏
  • 举报
回复
呵呵。c/c++做不到这个

15,440

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧