简体   繁体   English

指向数组中第一个元素的指针! (C)

[英]Pointer to first element in array! (C)

I'm new to C.我是 C 的新手。

I know this has been asked in many forms but mine is a little unique...I guess.我知道很多 forms 都问过这个问题,但我的有点独特……我猜。 I have an unsigned short pointer.我有一个无符号短指针。

6 unsigned short *pt;  
7 pt = myArray[0];

The array is declared as such: const unsigned short myArray[1024] and is an array of hex numbers of the form 0x0000 and so on.数组声明如下: const unsigned short myArray[1024]并且是 0x0000 等形式的十六进制数数组。

I try to compile, it throws these errors:我尝试编译,它会抛出这些错误:

myLib.c:7: error: data definition has no type or storage class
myLib.c:7: error: type defaults to 'int' in declaration of 'pt'
myLib.c:7: error: conflicting types for 'pt'
myLib.c:6: note: previous declaration of 'pt' was here
myLib.c:7: error: initialization makes integer from pointer without a cast

any ideas of what's going wrong?关于出了什么问题的任何想法?

Thanks, Phil谢谢,菲尔

My guess (you only show two lines) is that this code appears outside a function.我的猜测(您只显示两行)是此代码出现在 function 之外。 This is a statement:这是一个声明:

pt = myArray[0];

Statements must go in functions.语句必须在函数中使用 go。 Also, if myArray has type unsigned short[] , then you want to do one of these instead:此外,如果myArray的类型为unsigned short[] ,那么您想要执行以下操作之一:

pt = myArray;
pt = &myArray[0]; // same thing

& is the reference operator. &是参考运算符。 It returns the memory address of the variable it precedes.它返回它前面的变量的 memory 地址。 Pointers store memory addresses .指针存储memory 地址 If you want to "store something in a pointer" you dereference it with the * operator.如果您想“将某些内容存储在指针中”,您可以使用*运算符取消引用它。 When you do that the computer will look into the memory address your pointer contains, which is suitable for storing your value.当您这样做时,计算机将查看您的指针包含的 memory 地址,该地址适合存储您的值。

char *pc; // pointer to a type char, in this context * means pointer declaration
char letter = 'a'; // a variable and its value

pc = &letter; // get address of letter
// you MUST be sure your pointer "pc" is valid

*pc = 'B'; // change the value at address contained in "pc"

printf("%c\n", letter); // surprise, "letter" is no longer 'a' but 'B'

When you use myArray[0] you don't get an address but a value, that's why people used &myArray[0] .当您使用myArray[0]时,您得到的不是地址而是值,这就是人们使用&myArray[0]的原因。

Yeah, you really should include a bit more code so we can see the context.是的,您确实应该包含更多代码,以便我们可以看到上下文。

I don't quite get the error messages, but your code is not correct.我不太了解错误消息,但您的代码不正确。

Try:尝试:

pt = &myArray[0];

Or:或者:

pt = myArray + 0;

Or just:要不就:

pt = myArray;

Instead.反而。

You should not throw away the const qualifier;你不应该扔掉 const 限定符; so the pointer should have a const modifier.所以指针应该有一个 const 修饰符。

const unsigned short myArray[1024];
const unsigned short * pointer = myArray;  // set pointer to first element

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM