将代码C ++转换为C. [英] Convert code C++ to C

查看:92
本文介绍了将代码C ++转换为C.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想将此行转换为C.此行基本上是为数组中的每个元素赋值。有谁能够帮我?非常感谢你



Hello, I want to convert this line to C. This line is basically assigning each element in the array a value. Can anybody help me? Thank you so much

char *arr = new char[10] {'A', 'K', 'U', 'E', 'B', 'Z', 'D', 'O', 'M', 'Q'};





我是什么尝试过:



我想这样做但是没有用。





What I have tried:

I wanted to do this but it is not working.

char *arr=(char *)malloc(11*sizeof(char)){'A', 'K', 'U', 'E', 'B', 'Z', 'D', 'O', 'M', 'Q'};

推荐答案

解决方案1是正确的,并且可以正常工作:但请记住该代码将生成一个局部变量:字符数组将在堆栈上,而不是堆:它只会在您从当前函数返回之前存在,并且不能以任何方式返回到调用函数而不会导致挂起引用 。如果在当前函数之外需要数组,则必须使用 malloc 并将该数组复制到它返回的基于堆的区域。
Solution 1 is correct, and will work: however do remember that that code will generate a local variable: the array of chars will be on the stack, not the heap: it will only exist until you return from the current function, and cannot be returned to the calling function in any way without causing a "hanging reference". If the array is needed outside the current function, you must use malloc and copy that array into the heap based area it returns.


char arr[] = {'A', 'K', 'U', 'E', 'B', 'Z', 'D', 'O', 'M', 'Q'};





这就是你所需要的do。

你甚至可以使用sizeof(arr)测试代码,你将得到10



That is all you need to do.
You can even test the code using sizeof(arr) and you will get 10


这篇关于将代码C ++转换为C.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆