C language pointer space secured [closed]

Asked 2 years ago, Updated 2 years ago, 37 views

Do you want to improve this question?Edit your post to clarify the issue you are trying to resolve by adding details.

Closed 2 years ago.

Two years ago

The following is my program, but the execution results are not working.
I think either the for statement or malloc is strange, but I don't know.

problems:

If you enter one string less than 32 bytes from your keyboard that contains no spaces, create a program that lets malloc fill in the new string by increasing each character to two, display the new string, free up memory, and exit.

Example: "abc" → "aabbcc"

Current State Programs

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

int main(void){

  char*p,q[32];
  inti,k,j;

  printf("Input MOZI:");
  scanf("%s",q);

  i = strlen(q);

  p=(char*)malloc(sizeof(char)*i*2);
  if(p==NULL) {exit(1);}

   printf("%d\n", i);

  for(k=0;k<i;k++){
    for(j=0;j<2;j++){
   *p=*q;
   *p++;
    }
  j = 0;
  ++*q;

  }
  printf("%s\n",p);
  printf("%s\n",q);

  free(p);

}

c

2022-09-30 18:18

2 Answers

Try changing *p++ and ++*q to p++ and ++q.
You want to proceed with the pointer, not change the contents, right?
* refers to what the pointer points to.
By the way, strictly speaking, ++ should take precedence over *, so there is no problem with *p++, but I think you should remove the asterisk because it is confusing.


2022-09-30 18:18

At a glance, there are the following problems:
I won't point out anything in detail for you to learn, so please look it up yourself.

  • Not taking action to contain less than 32 bytes of input string to be retrieved
  • Not taking into account the length of data indicating the end of the string when securing space (@akiraejiri pointed out)
  • When copying each character, the original pointer itself is rewritten (so subsequent display and space release are not working)
  • No data is written indicating the destination string termination


2022-09-30 18:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.