pointer arithmetic in C for getting a string

你离开我真会死。 提交于 2019-12-20 06:28:16

问题


I want to get the elements of an array of characters, but no success at all, the problem is that I only get the first and last element and nothing more, my code is:

void getcharacters(char *cad)
{
 int l;
 int *i;
 l=strlen(cad);
 for (i=&cad[0];i<&cad[l];i++){
     printf("%c\n",*cad);
 }
}

any help? Thanks


回答1:


You are using the same character (*cad or cad[0]) for all printf's. What you need is to use the index to get the next char in each iteration. Also i needs to be a pointer to char:

void getcharacters(char *cad)
{
 int l;
 char *i;
 l=strlen(cad);
 for (i=&cad[0];i<&cad[l];i++){
     printf("%c\n", *i );
 }
}



回答2:


The size of an int can be as big as 4 x the size of a char, so when you do i++ you are actually skipping 3 chars.

Also, you print out *cad instead of *i.

To fix change i to char* and print *i instead of *cad




回答3:


Why don't you iterate from first character to the last one and accessing them as array index

int i;
int l=strlen(cad);
for (i=0;i<l;i++)
{
  printf("%c\n",cad[i]);
}



回答4:


Other answers have told you why it plain doesn't work, I'm wonder why you're not just iterating until the null terminator?

void getcharacters(char *cad)
{
 char *i;
 for (i = cad; *i; i++) {
     printf("%c\n",*i);
 }
}


来源:https://stackoverflow.com/questions/13852540/pointer-arithmetic-in-c-for-getting-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!