C中动态阵列的索引功能
我正在编写此片段的代码,该代码无需任何错误而使用,但是当我使用valgrind
运行它时,它会引发错误,有条件跳转或移动取决于非初始化的值
,这是由 循环试图访问数组中的第三个元素,
我的问题是我可以使用函数get_index()
,因为它在使用GCC -G -WALL -PESTONTIC MAIN.C ,并输出与
idx
相同的索引
#include <stdio.h>
#include <stdlib.h>
#define L 3
int *ptr;
int idx=0; // index
int get_index()
{
int x=0;
while(ptr[x])
x++;
return x;
}
void add_elem()
{
printf("Enter your number :\n");
scanf("%d",&ptr[idx]);
idx++;
}
int main(void) {
ptr = (int*)malloc(sizeof(int));
add_elem();
add_elem();
printf("Current index : %d\n",get_index());
printf("Original index : %d\n",idx);
return 0;
}
I am writing this piece of code which works without any errors but when I run it with valgrind
it throws errors that Conditional jump or move depends on uninitialized value
which is caused by the while
loop trying to access the third element in the array
My question is can I use the function get_index()
since it does not show any warnings or errors when compiling with gcc -g -Wall -pedantic main.c
and outputs the same index as the idx
which is declared globally
#include <stdio.h>
#include <stdlib.h>
#define L 3
int *ptr;
int idx=0; // index
int get_index()
{
int x=0;
while(ptr[x])
x++;
return x;
}
void add_elem()
{
printf("Enter your number :\n");
scanf("%d",&ptr[idx]);
idx++;
}
int main(void) {
ptr = (int*)malloc(sizeof(int));
add_elem();
add_elem();
printf("Current index : %d\n",get_index());
printf("Original index : %d\n",idx);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论