将指针转换回C中的数组 [英] Converting a pointer back to an array in C

查看:148
本文介绍了将指针转换回C中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数*getText(),其中最终结果是一个数组,我需要从该函数返回该数组.据我所知,这不可能直接实现,所以我创建了一个指针,如下所示:

char *ptr = &plainText[0];
return ptr;

我对C还是很陌生,并且对使用指针并不完全满意,因此我创建了一些代码以将指针转换回我需要的函数中的数组:

int i;
char plainText[256];
for (i=0; *(getText()+i) == '\0'; i++){
    plainText[i] = *(getText()+i);
}

这里的想法是for循环将遍历指针指向的字符串,直到找到结尾('\0'),并为每个字符追加字符串.

但是,尽管该程序在gcc中编译时没有编译器错误,但在到达此代码段时,它会中止而没有任何运行时错误.

任何人都可以给我一些指导,以使其正常工作吗?

詹姆斯

解决方案

如果仔细考虑,您会发现将指针转换为数组" 毫无意义.

数组是一个连续的内存块,您为其指定了一个名字 .

指针是内存地址.

您不能将指针转换为数组-您将如何突然将地址改回内存块?您需要创建一个新块,然后将想要复制的内容复制到那里.

当然,首先要指出的是原始对象存在.对于您来说,这似乎是一个本地数组,这意味着在您尝试将其数据复制到另一个数组时,它已被破坏.

I have a function *getText() where the end result is an array which I need to return from the function. As far as I'm aware, this isn't possible directly, so I created a pointer as follows:

char *ptr = &plainText[0];
return ptr;

I'm still fairly new to C and am not entirely comfortable working with pointers, so I created a little bit of code to convert the pointer back to an array in the function I need it in:

int i;
char plainText[256];
for (i=0; *(getText()+i) == '\0'; i++){
    plainText[i] = *(getText()+i);
}

The idea here is that the for loop will go through the string the pointer points to until it finds the end ('\0') and for every character, append the string.

However, although the program compiles in gcc with no compiler errors, it aborts without any runtime errors when it gets to this segment of code.

Could anyone give me some guidance on getting this to work?

James

解决方案

If you think about it carefully, you'll see that "converting a pointer to an array" makes no sense.

An array is a contiguous block of memory to which you gave a name.

A pointer is a memory address.

You can't convert a pointer to an array -- how would you suddenly change an address back to a block of memory? You would need to instead create a new block, and copy whatever you want to there instead.

Provided, of course, that the original pointee exists in the first place. In your case, it seems like it's a local array, which means that it is destroyed by the time you try to copy its data to another array.

这篇关于将指针转换回C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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