zoukankan      html  css  js  c++  java
  • malloc_in_function.c

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 
     5 void malloc_in_function(char **myArray, int size)
     6 {
     7   int i = 0;
     8 
     9   *myArray = (char *) malloc(size * sizeof(char));
    10   if (*myArray == NULL)
    11   {
    12     fprintf(stderr, "Error allocating memory for myArray!\n");
    13     exit(0);
    14   }
    15 
    16   /* this is how to access array members in the function */
    17   for (i = 10; i < 20; i++)
    18   {
    19     /* This line will cause a segmentation fault. Why? */
    20       /* *myArray[i] = 'a' + (i - 10); */
    21 
    22     /* This line works much better. */
    23     (*myArray)[i] = 'a' + (i - 10);
    24   }
    25 }
    26 
    27 int main(int argc, char **argv)
    28 {
    29   /* char myArray[20]; */
    30   char *myArray;
    31   int size = 20;
    32   int i = 0;
    33 
    34   malloc_in_function(&myArray, size);
    35 
    36   for (i = 0; i < 10; i++)
    37   {
    38     myArray[i] = 'A' + i;
    39   }
    40     
    41   for (i = 0; i < 20; i++)
    42   {
    43     printf("myArray[%d] = %c\n", i, myArray[i]);
    44   }
    45 
    46   free(myArray);
    47 }
    48 
    49 /* in main(), what does (myArray + 10) and &myArray[10] have in common?
    50  * What about *(myArray + 10) and myArray[10]?
    51  * What is *myArray + 10? Is it the same as myArray[0] + 10?
    52  * If the malloc was for an int, would (myArray + 10) be the same as &myArray[10]?
    53  */
  • 相关阅读:
    div居中方法总结
    windows下配置nginx环境
    webpack+babel+react操作小结
    JavaScript数组常用操作总结
    MyBatis使用Generator自动生成代码
    如何上Chrome谷歌商店
    深入理解Spring IOC
    SpringMVC概要总结
    mybatis防止sql注入
    Redis和Memcache的区别分析
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/12805759.html
Copyright © 2011-2022 走看看