这段代码是malloc函数和动态数组操作的练习,非常简单:程序必须为255个无符号字符分配255字节的内存(与普通整数的不同之处在于字符只占一个字节,所以当我不需要大于255的数字时,我保存了内存,这只是一个细节),然后它询问用户在写入0之前,他想对该数组做什么,现在的选项只有3.一个非常简单的练习,让我学习使用动态数组,但有一个问题,我不明白!当我分配内存一切顺利,直到执行扫描函数:在扫描变量“select”之后,数组指针变为NULL,我不知道为什么。这不可能是内存冲突问题,因为数组不会被存储。我该怎么办?
这里的代码,并提前感谢帮助:
#include <stdio.h>
#include <stdlib.h>
#define TRY
void main(){
//the array is dinamically allocated in the heap memory and when it has a valid address the program starts
unsigned char select = 1; //this variable is useful for the choice of the utent
unsigned char length = 0; //this has no need to be explained
unsigned char index = 0; //this variable can be used as temporary variable in the program
unsigned char * array = (unsigned char*)malloc(255);
if(array){
while(select){
#ifdef TRY
printf("\t- - Array stored in %p memory address - -\n", array);
#endif
printf("What wanna do?\n1 - show array\n2 - insert value\n3 - edit value\n0 - quit\n");
scanf("%d", &select);
//generally the problems start from here: after the scanf the pointer turns into a NULL, you can see by the execution of the next line
#ifdef TRY
printf("\t- - Array stored in %p memory address - -\n", array);
#endif
switch(select){
case 0: printf("Bye!\n");
break;
case 1:
printf("Elements: %u\n", length);
for(index = 0; index < length; index++) printf("%d\t", *(array+index));
break;
case 2:
if(length<255){
printf("Write the value to insert in the %p memory address: ", array+length);
scanf("%d", (array+length));
printf("Value %d added in %p address\n", *(array+length), array+length);
length = length+1;
}
else
printf("Array is full\n");
break;
case 3:
printf("Write the index value: ");
scanf("%d", &index);
if(index<length){
printf("Write the value to insert in the %p memory address: ", array+index);
scanf("%d", array+index);
printf("Value %d written in %p address\n", *(array+length), array+length);
}
else
printf("Invalid index\n");
break;
default: printf("Invalid input\n");
break;
}
}
free(array);
}
else printf("Memory error\n");
}
我还尝试用同样的malloc函数分配同一个数组中的其他变量,解释得更好,我创建了三个unsigned char指针而不是前三个unsigned char变量,并将数组最后三个字节的地址赋给它们,指针不再为NULL,但数组总是空的:在数组中插入一个值后,每次程序在“选择”时使用扫描函数,数组总是被清空。2问题总是相同的。
1条答案
按热度按时间3bygqnnd1#
编译时出现警告:
在扫描完变量“select”之后,数组指针变为NULL,我不知道为什么
可能
scanf
在您希望接收一个字节的地方写入了4个字节,覆盖了连续的内存区域。要扫描
unsigned char
交换机以:与
array
和index
相同