使用malloc时什么都没有指针?

0 c arrays malloc pointers segmentation-fault

据我所知,我已经遵循了其他用户提供的建议,但是当我尝试返回指向数组的指针时,我仍然会遇到段错误.main中的printf什么也没有返回,所以我猜测指针不是堆上的任何东西?

#include <stdio.h>
#include <stdlib.h>

int * stringy(int length){
   int *ptr = malloc(sizeof(int)*length);
   int i;
   for(i = 0; 1 < length; i++){
      ptr[i] = i;
   }
   return(ptr);
}

void main(int argc, char **argv){
   int strlen = 12;
   int *newptr = stringy(strlen);
   printf("%d\n",newptr[0]);
   free(newptr);
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*vis 6

好像你的代码中有一个拼写错误.代替

for(i = 0; 1 < length; i++){
Run Code Online (Sandbox Code Playgroud)

,看起来你的意思

for(i = 0; i < length; i++){
Run Code Online (Sandbox Code Playgroud)

  • 不要强制转换`malloc`.这毫无意义.请参阅:[**我是否会转换malloc的结果?**](http://stackoverflow.com/q/605845/995714)以获得详尽的解释. (2认同)
  • 提供不好的建议以及善意会使这个问题变得糟糕.在某些方面,比整个事情都糟糕的更糟糕的答案. (2认同)