簡體   English   中英

C中用戶輸入的指針指針字符串(char **)

[英]pointer pointer string (char **) from user input in C

我是C語言的新手,出於我需要的目的,我似乎在指針指針char上找不到太多內容。 這是我的簡化代碼:

int total, tempX = 0;
printf("Input total people:\n");fflush(stdout);
scanf("%d",&total);

char **nAmer = (char**) malloc(total* sizeof(char));

double *nUmer = (double*) malloc(total* sizeof(double));;

printf("input their name and number:\n");fflush(stdout);

for (tempX = 0;tempX < total; tempX++){
    scanf("%20s %lf", *nAmer + tempX, nUmer + tempX); //I know it's (either) this
}
printf("Let me read that back:\n");
for (tempX = 0; tempX < total; tempX++){
    printf("Name: %s Number: %lf\n",*(nAmer + tempX), *(nUmer + tempX)); //andor this
}

我不確定在獲取用戶輸入時指針指標char的正確格式是什么。 如您所見,我正在嘗試獲取人們的姓名及其號碼的列表。 我知道數組,矩陣和類似的東西很容易,但是它只能是一個指針指針。 謝謝!

如果要存儲N個字符串(每個字符串最多20個字符),則不僅需要分配用於指向字符串的指針的空間,還需要分配用於存儲字符串本身的空間。 這是一個例子:

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

int main(int argc, char ** argv)
{
   int total, tempX = 0;

   printf("Input total people:\n");fflush(stdout);
   scanf("%d",&total);
   printf("You entered:  %i\n", total);

   // note:  changed to total*sizeof(char*) since we need to allocate (total) char*'s, not just (total) chars.
   char **nAmer = (char**) malloc(total * sizeof(char*));
   for (tempX=0; tempX<total; tempX++)
   {
      nAmer[tempX] = malloc(21);  // for each string, allocate space for 20 chars plus 1 for a NUL-terminator byte
   }

   double *nUmer = (double*) malloc(total* sizeof(double));;

   printf("input their name and number:\n");fflush(stdout);

   for (tempX = 0; tempX<total; tempX++){
       scanf("%20s %lf", nAmer[tempX], &nUmer[tempX]);
   }

   printf("Let me read that back:\n");
   for (tempX = 0; tempX<total; tempX++){
       printf("Name: %s Number: %lf\n", nAmer[tempX], nUmer[tempX]);
   }

   // Finally free all the things we allocated
   // This isn't so important in this toy program, since we're about
   // to exit anyway, but in a real program you'd need to do this to
   // avoid memory leaks
   for (tempX=0; tempX<total; tempX++)
   {
      free(nAmer[tempX]);
   }

   free(nAmer);
   free(nUmer);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM