我只是想教自己如何创建、改变传递指针和使用内存池中的内存块。我在下面的程序中尝试的是从内存池(我malloc
编辑的)返回一个指向内存块的指针,但是它给了我一个错误。如果有人可以通过解释我的错误来为我指明正确的方向,向我展示如何解决它(或引导我朝着正确的方向前进),那就太棒了!
这是我现在拥有的代码(下面是我的错误消息):
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
int EnemyLife(int level)
{
int RandTime;
int *ptr;
srand(time(NULL));
ptr = (int*) malloc(sizeof(int)*level);
for (int i = 0; i < level; ++i)
{
RandTime = rand() % 100;
*ptr++ = RandTime;
}
return *ptr;
};
int main(void)
{
int Ammount, RandValue;
int (*PtrEnemyLife) (int) = EnemyLife;
printf("Ammount of random number printed to the screen?\n");
scanf("%d", &Ammount);
int *ptr;
*ptr = (*PtrEnemyLife) (Ammount);
printf("%d\n", *ptr);
return 0;
}
...这是我在同行建议我使用-Wall
标志编译后得到的错误。
/home/definity/Desktop/Cloud/code/rand.c: In function ‘main’:
/home/definity/Desktop/Cloud/code/rand.c:39:7: warning: ‘ptr’ is used uninitialized in this function [-Wuninitialized]
/home/definity/Desktop/Cloud/code/rand: In function `EnemyLife':
/home/definity/Desktop/Cloud/code/rand.c:8: multiple definition of `EnemyLife'
/tmp/ccvZvKYA.o:/home/definity/Desktop/Cloud/code/rand.c:8: first defined here
/home/definity/Desktop/Cloud/code/rand: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
/home/definity/Desktop/Cloud/code/rand: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
/home/definity/Desktop/Cloud/code/rand: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/4.7/crtbegin.o:(.data+0x0): first defined here
/home/definity/Desktop/Cloud/code/rand:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
/home/definity/Desktop/Cloud/code/rand: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here
/home/definity/Desktop/Cloud/code/rand: In function `main':
/home/definity/Desktop/Cloud/code/rand.c:28: multiple definition of `main'
/tmp/ccvZvKYA.o:/home/definity/Desktop/Cloud/code/rand.c:28: first defined here
/home/definity/Desktop/Cloud/code/rand: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/usr/lib/gcc/x86_64-linux-gnu/4.7/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__'
/home/definity/Desktop/Cloud/code/rand:(.data+0x10): first defined here
/usr/bin/ld: error in /home/definity/Desktop/Cloud/code/rand(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status
[Finished in 0.1s with exit code 1]