使用指针计算长度 [英] calculate length using pointer

查看:162
本文介绍了使用指针计算长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算字符串的长度,但我没有办法在C中计算该长度,但是在使用C#时遇到错误,这是我的代码,请解决我的问题

字符串a =我是穆萨米尔·哈桑";
字符串* ptr =&a;
int c = 0;
while(* ptr!= null)
{
c ++;
}

i am trying to calculate length of a string and i no how to calculate that in C but i am facing error when using C# this is my code please solve my problem

string a = "i am muzamil hassan";
string *ptr =&a;
int c = 0;
while (*ptr != null)
{
c++;
}

推荐答案

string a = "i am muzamil hassan";
int c = a.Length;


要在C#中使用指针执行此操作,就意味着您需要运行unsafe代码-对于如此简单的工作不是必需的!


To do it in C# using pointers means that you need to be running unsafe code - not necessary for such a simple job!


好吧,如果我想计算多少次字母一个''来,所以我如何使用指针来做到这一点,我使用关键字unsafe
ok if i want to calculate like how many times letter "a'' comes so how i do that with using pointer i use keyword unsafe


似乎您将C#与C或C ++混合使用.C#字符串的长度为System.String.Length.请参见 http://msdn.microsoft.com/en-us/library/system.string.aspx [ ^ ].

这个问题在C#中根本没有任何意义.即使使用C ++,您也可以使用std::string,它也支持它的长度.

使用C#,您甚至不能使用指针,除非您使用不安全代码并 pin 一个对象.现在看来,这个主题对您来说太高级了.您需要学习C#和.NET的基础知识.它使用引用的概念工作,这与指针不太相同,主要是由于自动垃圾回收(GC).

—SA
It looks like you mixed up C# with C or C++. C# strings carry the length as System.String.Length. See http://msdn.microsoft.com/en-us/library/system.string.aspx[^].

The question makes no sense in C# at all. Even with C++ you could use std::string which also support its length.

With C#, you cannot even use pointers unless you use unsafe code and pin an object. It looks like this topic is too advanced for you right now. You need to learn the very basics of C# and .NET. It works with the concept of reference, which in not quite the same as pointer, mostly because of automatic Garbage Collection (GC).

—SA


这篇关于使用指针计算长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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