C中动态阵列的索引功能

发布于 2025-01-20 04:33:12 字数 764 浏览 2 评论 0原文

我正在编写此片段的代码,该代码无需任何错误而使用,但是当我使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文