二维数组和指针 [英] 2D arrays and pointers

查看:139
本文介绍了二维数组和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我是一个新手的指针,并在以下code,我想一个2维数组的值存储在一个结构,然后打印出来。不过,我在该行得到一个编译错误:F D-> mychar [I] = NEWPTR [I]; 我得到的,而字符* STR 是一样的海峡[] 的char ** STR 心不是一样海峡[] [] ,但我不能找到一个解决方案,使下面的工作。

  typedef结构MYSTRUCT {
  炭mychar [20] [20];
} mystruct_t;无效函数printValues​​(字符** NEWPTR){
  INT I;
  mystruct_t * FD;
  对于(I = 0; I&下; 3;我++){
    FD-GT&; mychar [I] = NEWPTR [I]
    的printf(我的值是%s和结构中的%S \\ n,NEWPTR [I],FD-GT&; mychar [I]);
  }
}
INT主(INT ARGC,字符** argv的){
 INT I;
 字符* ABC [5] = {123,456,789}; 对于(I = 0; I&下; 3;我++){
  的printf(我的值是%S \\ n,ABC [I]);
 }
 函数printValues​​(ABC);
}


解决方案

大部分的问题是你的未分配结构的使用。
你用一个指针mystruct_t但从来没有分配它。
对我来说,以下运行:

 的#include<&stdio.h中GT;typedef结构MYSTRUCT
{
   字符* mychar [20];
} mystruct_t;无效函数printValues​​(字符** NEWPTR)
{
   INT I;
   //注意:您在最初的code使用的未分配的指针
   mystruct_t FD;
   对于(I = 0; I&下; 3;我+ +)
   {
      fd.mychar [I] = NEWPTR [I]
      的printf(我的值是%s和结构中的%S \\ n,NEWPTR [I],fd.mychar [I]);
   }
}INT主(INT ARGC,字符** argv的)
{
   INT I;
   字符* ABC [5] = {123,456,789};   对于(I = 0; I&下; 3;我+ +)
   {
      的printf(我的值是%S \\ n,ABC [I]);
   }
   函数printValues​​(ABC);
}

Hey All, I am a pointer newbie and in the following code, I am trying to store the values of a 2 D array in a structure and then print them. However, I get a compilation error at the line: fd->mychar[i] = newptr[i]; I get that while char * str is same as str[], char ** str isnt the same as str[][], but I cant find a solution to make the following work.

typedef struct mystruct{
  char mychar [20][20];
}mystruct_t;

void printvalues ( char ** newptr){
  int i;
  mystruct_t * fd;
  for (i=0;i<3;i++){
    fd->mychar[i] = newptr[i];
    printf("My value is %s and in struct %s\n", newptr[i], fd->mychar[i]);
  }
}
int main (int argc, char **argv){
 int i;
 char * abc[5] = {"123", "456", "789"};

 for (i=0;i<3;i++){
  printf("My value is %s\n", abc[i]);
 }
 printvalues(abc);
}

解决方案

Most of the issue was your use of an unallocated structure. You used a pointer to mystruct_t but never allocated it. The following runs for me:

#include <stdio.h>

typedef struct mystruct
{
   char*  mychar [20];
} mystruct_t;

void printvalues( char** newptr )
{
   int i;
   // note: you used an unallocated pointer in your original code
   mystruct_t fd;
   for ( i = 0; i < 3; i++ )
   {
      fd.mychar[i] = newptr[i];
      printf( "My value is %s and in struct %s\n", newptr[i], fd.mychar[i] );
   }
}

int main( int argc, char **argv )
{
   int i;
   char * abc[5] = { "123", "456", "789" };

   for ( i = 0; i < 3; i++ )
   {
      printf( "My value is %s\n", abc[i] );
   }
   printvalues( abc );
}

这篇关于二维数组和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆